Wednesday, February 22, 2012

Display MySql data using JSON and AJAX in PHP


This program is for implementing AJAX concept with JSON Technology . It will display roll number from database without reloading page. My database fields  are
·         Name
·         Surname
·         Roll

    Output:-


My Database table:-

Step 1) Copy the following code and paste it in your PHP page

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script language="javascript">
function ajax()
{
 var name=document.myform.name.value;

 var xmlhttp=new XMLHttpRequest();
 if(xmlhttp=="")
   {
     alert("Object not created");
   }
  else
  {
                //ajax object creaTED.......
    xmlhttp.onreadystatechange=function()
    {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
       {
                                 var jsonText = xmlhttp.responseText
                                 var jsonObject= eval('('+jsonText+')');
                                 
                                 var sur=jsonObject.surname;
                                 var rol=jsonObject.roll;

                                document.myform.surname.value=sur;
                                document.myform.roll.value=rol;

       }
    }
   xmlhttp.open("GET","ajax.php?name="+name,true);
   xmlhttp.send();

  }
}
</script>
</head>
<body>
<form name="myform" method="post">
<table>
<tr>
  <td>Enter name:-</td>
  <td><input type="text" name="name"></td>
</tr>

<tr>
  <td>Surname:-</td>
  <td><input type="text" name="surname"></td>
</tr>


<tr>
  <td>Roll:-</td>
  <td><input type="text" name="roll"></td>
</tr>
</table>
<input type="button" onClick="ajax()" value="Get roll">
<input type="reset" value="clear">
</form>
</body>
</html>

Step 2)Open a PHP file , name it ajax.php and change the necessary coding according to your database setting.

<?php
$name1=$name;
$conn=mysql_connect("localhost","root","");
$ans=mysql_select_db("ajax",$conn);
if($conn=="" || $ans=="")
{
  echo "Database connection error";
}
else
{
  $qur="select * from stud where name='$name1'";
  $ans=mysql_query($qur);
  while($row=mysql_fetch_array($ans))
  {
    $ur=$row['roll'];
                $us=$row['surname'];
  }
   $ans=Array("surname" => $us,"roll" => $ur);
  $json_name=json_encode($ans);
  echo $json_name;
}
?>

3 comments:

  1. thanks man this is awesome. you have solve my biggest problems which took my 4 days..

    ReplyDelete
  2. Thanks man , you saved my life

    ReplyDelete