To retrieve data from MYSQL or any database using AJAX, you need to do the following steps
Step 1
Create a database db_test and add one table named test with the following fields
name
username
department
phone
Step 2
Insert some dummy values into the table TEST manually.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Step 3
Create one HTML page index.html and add the following code into that HTML page.
<html>
<title>Code from www.jijokjose.com</title>
<head>
<script type="text/javascript">
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="users" onChange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</form>
<br />
<div id="txtHint"><b>Person info will be listed here.</b></div>
</body>
</html>
Step 4
Create one PHP page getuser.php and add the following code into that PHP page.
<?php
$q=$_GET["q"];
$conn=mysql_connect("localhost", "root", "") or die("Unable to connect");
mysql_select_db('db_test',$conn);
$sql="SELECT * FROM test WHERE username = '".$q."'";
$result = mysql_query($sql);
echo "<table border='1'>
<tr>
<th>Name</th>
<th>Username</th>
<th>Department</th>
<th>Phone</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['username'] . "</td>";
echo "<td>" . $row['department'] . "</td>";
echo "<td>" . $row['phone'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
Step 5
Open index.html file from WAMP server and select one username from the list box then it display the corresponding user details automatically.
No comments:
Post a Comment