Home >>Ajax Tutorial >Display Data Using Ajax

How To Display Data Using Ajax in PHP

JavaScript function send request to server and Get Response

<script>
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","getdatafromDB.php?q="+str,true); xmlhttp.send(); }
</script>

<select name="users" onchange="showUser(this.value)">
<option disabled="disabled" selected="selected" value="">Select a person:</option>
<option value="1">vikash</option>
<option value="2">Ravi</option>
<option value="3">Sandeep</option>
<option value="4">Saurabh</option>
</select>

<div id="txtHint" style="width: 400px; border: 2px solid red;"><b>Person info will be listed here.</b></div>

PHP Script Send Respons to JavaScript

<?php
$con = mysql_connect('localhost', 'root', '');
mysql_select_db("test", $con);
$q=$_GET["q"];
$sql="SELECT * FROM stuinfo WHERE stu_id ='$q'";

$result = mysql_query($sql);

echo "<table border='1'>
<tr>
<th>Email </th>
<th>Mobile</th>
</tr>";

while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['mobile'] . "</td>";
echo "</tr>";
}
echo "</table>";

mysql_close($con);
?>
?>

Popular Tutorials