simple ajax example in php

AJAX stands for Asynchronous Javascript And XML. With ajax, we do need to submit whole form to php, rather, we can send information from a portion of form and receive the response. In this way, the communication cost and delay in submitting the form and receiving response can be significantly reduced.

The following program uses three files:

default.php :

This file is our main web page from which we send information to server side, using ajax. In our case, we are passing an ID to javascript function, and against that ID we want to receive the name of the user

ajax_javascript.php :

This file creates an ajax object, using which we communicate with the backend php file

ajax_file.php :

This file contains the server side logic. It receives the values of parameters sent by javascript file and “echo” the response. It is important to note that only one value can be echoed from php file at a time. This file DOES NOT return any value

Here is code of the files. For database, you can use the same code/database as used in previous examples.



<script type="text/javascript" src="ajax_javascript.js"></script>
<form id="frm" name="frm" method="post" action="">
<input id="btn" name="btn" value="click" onclick="ShowMessage(1);" type="button">


<label id="label1"></label>

<div id="div1">



function ShowMessage(id)


if (xmlHttp==null)
  alert ("Your browser does not support AJAX!");
}"POST", "ajax_file.php", true);

///////// Function getting values back from php file /////////////////////////
  if (xmlHttp.readyState==4)
    var response = xmlHttp.responseText;	


// Make our POST parameters string…
  var params = "id=" + encodeURI(id);

  // Set our POST header correctly…
  xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xmlHttp.setRequestHeader("Content-length", params.length);
  xmlHttp.setRequestHeader("Connection", "close");

  // Send the parms data…

//////////////////////////////// Return the appropriate Ajax object  //////////////////////////////////////////
function GetXmlHttpObject()
var xmlHttp=null;
  // Firefox, Opera 8.0+, Safari
  xmlHttp=new XMLHttpRequest();
catch (e)
  // Internet Explorer
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
  catch (e)
    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
return xmlHttp;



$id = $_POST['id'];	
$query = "select * from stdrecord where stdid=".$id;
$stmt = $conn -> prepare($query);
$stmt -> execute();

$str = "<table border='1'>";

while($row = $stmt->fetch())
$str = $str . "<tr><td>$row[0]</td><td>$row[1]</td></tr>";
$str = $str . "</table>";

echo $str;
$conn = NULL;



Add a Comment

Your email address will not be published. Required fields are marked *