How to send and receive data using Ajax

Ajax ProgrammingWhat is Ajax? – An introduction to Ajax

Like the desktop applications where the data transfer between the client and the server side is seamless without any visible refresh, Ajax gives you the power to do the same on web based applications.

When you press a Submit button on a web page or a click a link, a request is sent to the server in a visible format and the whole page reloads. This is where Ajax comes in. It allows you to dynamically change a part of the page, or the whole page, without any visible refresh or flicker. The data transfer is so seamless and smooth that in some cases, you may not notice the change.

Ajax stands for “Asynchronous JavaScript and XML”.

Ajax is primarily based on JavaScript. JavaScript is a language which is loaded into the browser and allows you to perform various actions with the web page and its elements. For those of you who don’t know the basics of JavaScript, you might want to first learn at least the core of JavaScript and then refer to this article to have a basic understanding of Ajax.

We’ll now step into how Ajax actually works. It consists of series of steps. The Ajax code, which is composed of JavaScript statements, loads into the browser when the page loads. Now when a data transfer is requested by the user (pressing a button or clicking a link), or an event occurs, the Ajax code goes into action. It opens an invisible connection to the server side (usually with a server side scripting language like php, jsp, or asp) and sends a request. The server responds to the request. That request is then handled back by the Ajax code (JavaScript code) and an appropriate action is taken according to the response from the server side.

The “Asynchronous” mean that it can send/receive the data without having to wait for other requests or calls (data requests to server). “XML” – The Extensible Markup Language – is used here to receive that data/response sent by the server in a proper format. It is similar to HTML.

How to send and receive data using Ajax

Let’s now move to the more interesting part of this article – how Ajax can be used to send and receive data dynamically, without any visible refresh.

This section assumes that you know the basics of JavaScript, Php, HTML and a little about XML.

1- Create an HTML file with any name you want, like “ajax.html”, and add the following code to it:

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml”>

<head>

<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />

<title>Simple Ajax Example</title>

<script type=”text/javascript” language=”javascript”>

function getXMLHttpRequestObject()

{

// initially set the object to false

var XMLHttpRequestObject = false;

if (window.XMLHttpRequest)

{

// check for Safari, Mozilla, Opera…

XMLHttpRequestObject = new XMLHttpRequest();

}

else if (window.ActiveXObject)

{

// check for Internet Explorer

XMLHttpRequestObject = new ActiveXObject(“Microsoft.XMLHTTP”);

}

if (!XMLHttpRequestObject)

{

alert(“Your browser does not support Ajax.”);

// return false in case of failure

return false;

}

// return the object in case of success

return XMLHttpRequestObject;

}

// get the XMLHttpRequestObject and store it in a variable

var ajaxObj = getXMLHttpRequestObject();

// function called when Check Name button is pressed

function checkName()

{

// continue if the ajaxObj object exists

if(ajaxObj)

{

// continue if the object is idle

if (ajaxObj.readyState == 4 || ajaxObj.readyState == 0)

{

// refer to the input text field

var inputObject = document.getElementById(‘inputbox’);

// build the “GET” request URL

var URL = “serverSide.php” + “?name=” + inputObject.value;

// open connection and send “GET” request to server

ajaxObj.open(“GET”, URL, true);

// set the function to be called on a change in ajaxObj state

ajaxObj.onreadystatechange = handleResponse;

// set additional parameters (to be sent to server) to null

ajaxObj.send(null);

}

}

}

// function called when there is a change ajaxObj state

function handleResponse()

{

// check if the request is complete

if (ajaxObj.readyState == 4)

{

// continue if the response is healthy

if (ajaxObj.status == 200)

{

// store the server’s text response

var textResponse = ajaxObj.responseText;

// get control of the “display” div

var displayObj = document.getElementById(“display”);

// display the message in the div

displayObj.innerHTML = textResponse;

}

}

}

</script>

</head>

<body>

<p>Enter Name:

<input type=”text” id=”inputbox” />

</p>

<p>

<input type=”button” name=”submit” value=”Check Name” onclick=”checkName();”/>

</p>

<div id=”display”></div>

</body>

</html>

 

2- Create a file called “serverSide.php” and add the following code to it:

<?php

if (trim($_GET[‘name’]) == “”)

{

echo “No name specified.”;

}

else

{

$name = $_GET[‘name’];

if ($name == ‘John’ || $name == ‘Bill’ || $name == ‘Ted’)

{

echo “The name ‘”. $name .”‘ was found in our database.”;

}

else

{

echo “The name ‘”. $name .”‘ does not exist in our database.”;

}

}

?>

Place both files in the same directory of your web host. It can be a localhost, or on the internet, but it should support PHP. You cannot place the file in your windows file system, without any localhost, since in that case the “serverSide.php” will not work.

The above script shows you a basic working example of the power of Ajax. So when you open the html file, you will see a text box and a button below labeled as “Check Name”. When you press the button, an invisible request is sent to the server to check if the name entered in the text box exists in the server’s database or not. In either case the response from the server is displayed in a DIV below the button. See how smoothly everything goes – no visible refresh or flicker of the browser and the web page is dynamically updated. Try playing with the CHECK NAME button for different names. For example put any name in the text box and then press the button. If the name you entered matches with that of the server’s database, it will say: “The name John was found in our database. (Server has the names ‘John’, ‘Bill’, ‘Ted’).”. In case you entered any other name, it will say “The name ‘Kamran’ does not exist in our database.” or if you leave it blank it will respond with “No name specified.”. These responses all come from the server side via the file named “serverSide.php”.

After having an overview of the above example, let’s now analyze the code to get a clearer picture. First we will look into the HTML file we have created.

The code lines explained below follow one another from top to bottom.

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml”>

<head>

<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />

<title>Simple Ajax Example</title>

 

Starting from the top of the HTML document: The lines above are the header part of the HTML document. They do not need any explanation as they are well known to you.

<script type=”text/javascript” language=”javascript”>

……. JavaScript code ……

</script>

 

This line is where the JavaScript begins. This line tells the browser that we are going to put some JavaScript code into the HTML document so the browser renders anything contained within these tags as JavaScript code.

function getXMLHttpRequestObject()

{

// initially set the object to false

var XMLHttpRequestObject = false;

if (window.XMLHttpRequest)

{

// check for Safari, Mozilla, Opera…

XMLHttpRequestObject = new XMLHttpRequest();

}

else if (window.ActiveXObject)

{

// check for Internet Explorer

XMLHttpRequestObject = new ActiveXObject(“Microsoft.XMLHTTP”);

}

if (!XMLHttpRequestObject)

{

alert(“Your browser does not support Ajax.”);

// return false in case of failure

return false;

}

// return the object in case of success

return XMLHttpRequestObject;

}

 

The above code is the core of Ajax. This function will return the “XMLHttpRequest” object required to send the request to the server and then handle the response.

function getXMLHttpRequestObject()

{….

 

This is the start of the function that will give us the object.

  // initially set the object to false

var XMLHttpRequestObject = false;

 

A variable is defined with a ‘false’ value that will store the “XMLHttpRequest”.

  if (window.XMLHttpRequest)

{

// check for Safari, Mozilla, Opera…

XMLHttpRequestObject = new XMLHttpRequest();

}

else if (window.ActiveXObject)

{

// check for Internet Explorer

XMLHttpRequestObject = new ActiveXObject(“Microsoft.XMLHTTP”);

}

 

Here is where a little trouble begins. The “XMLHttpRequest” object is browser inconsistent. Which means that the same method can not be used to get the “XMLHttpRequest” object on all major browsers. Safari, Mozilla and Opera have the same method of getting the “XMLHttpRequest” object while Internet Explorer has its own. However rest assured it is the object of the browser’s window. So the code starts with:

 

  if (window.XMLHttpRequest)

{

// check for Safari, Mozilla, Opera…

XMLHttpRequestObject = new XMLHttpRequest();

}

This conditional statements checks if the browser supports “window.XMLHttpRequest” and if it does it assigns the  “XMLHttpRequest” object to the variable “XMLHttpRequestObject” in the statement:

XMLHttpRequestObject = new XMLHttpRequest();

 

The new XMLHttpRequest(); creates an instance of browser window’s “XMLHttpRequest” object. This is supported by all modern versions of Mozilla FireFox, Safari, Opera etc.

If the conditional statement returns false the control moves onto the …elseif… statement.

  else if (window.ActiveXObject)

{

// check for Internet Explorer

XMLHttpRequestObject = new ActiveXObject(“Microsoft.XMLHTTP”);

}

 

This conditional statement then checks (after the initial statement is returned false) if the browser supports “ActiveX Objects” by the statement “window.ActiveXObject”. It returns true for Internet Explorer since it has the  “XMLHttpRequest” object as an ActiveX object.

The statement  XMLHttpRequestObject = new ActiveXObject(“Microsoft.XMLHTTP”); then assigns the  “XMLHttpRequest” object to the variable.

Notice the new ActiveXObject(“Microsoft.XMLHTTP”); . IE creates an instance of the XMLHttpRequest” object in this way “Microsoft.XMLHTTP” is the standard version of the Microsoft’s “XMLHttpRequest” object.

 

  if (!XMLHttpRequestObject)

{

alert(“Your browser does not support Ajax.”);

// return false in case of failure

return false;

}

 

The above statement checks if the “XMLHttpRequest” object stored in “XMLHttpRequestObject” variable is valid. If not, it alerts the user and returns false and the function exits. In case the “XMLHttpRequest” object is supported by the browser the above statements are skipped and the control moves onto last statement.

 

  // return the object in case of success

return XMLHttpRequestObject;

 

This statement returns the variable holding the “XMLHttpRequest” object.

When the browser loads this statement is executed automatically since it is outside any function’s scope.

// get the XMLHttpRequestObject and store it in a variable

var ajaxObj = getXMLHttpRequestObject();

 

What this statement does is call the “getXMLHttpRequestObject()” function already explained. The function upon execution returns either the “XMLHttpRequest” object or a false response. This value/object returned by the function is then assigned to the “ajaxObj” variable.

// function called when Check Name button is pressed

function checkName()

{

// continue if the ajaxObj object exists

if(ajaxObj)

{

// continue if the object is idle

if (ajaxObj.readyState == 4 || ajaxObj.readyState == 0)

{………….

 

“checkName()” is the name of the function called/executed when the “Check Name” button is pressed.    

 

if(ajaxObj)

{…

This statement checks if the ajaxObj is true/valid since in other case we cannot continue.

      if (ajaxObj.readyState == 4 || ajaxObj.readyState == 0)

{………….

 

The “XMLHttpRequest” object has many properties and methods. The most common properties are listed below:

Common XMLHttpRequest Object Properties

  • onreadystatechange
    Holds the name of the event handler that should be called when the value of the readyState property changes.
  • readyState
    Holds the state of the request.
  • responseText
    Holds the response body as a string.
  • responseXML
    Holds the response body as XML.
  • status
    Holds the HTTP status code returned by a request.
  • statusText
    Holds the HTTP response status text.

Common XMLHttpRequest Object Methods

  • abort
    Aborts the HTTP request.
  • getAllResponseHeaders
    Gets all the HTTP headers.
  • getResponseHeader
    Gets the value of an HTTP header.
  • open
    Opens a request to the server.
  • send
    Sends an HTTP request to the server.
  • setRequestHeader
    Sets the name and value of an HTTP header.

Now the conditional statement below checks the state of the “XMLHttpRequest” object to see if it is available to send an invisible request to the server.

 

 if (ajaxObj.readyState == 4 || ajaxObj.readyState == 0)

{………….

The “XMLHttpRequest” object has the property “readyState” which may have the following values (0, 1, 2, 3, 4):

 

0 -> uninitialized

1 -> loading

2 -> loaded

3 -> interactive/transition state

4 -> complete

 

So we are concerned with the state “0” and “4”. If any of the object is in any of these two states we are ready to move next.

// refer to the input text field

var inputObject = document.getElementById(‘inputbox’);

// build the “GET” request URL

var URL = “serverSide.php” + “?name=” + inputObject.value;

// open connection and send “GET” request to server

ajaxObj.open(“GET”, URL, true);

// set the function to be called on a change in ajaxObj state

ajaxObj.onreadystatechange = handleResponse;

// set additional parameters (to be sent to server) to null

ajaxObj.send(null);

var inputObject = document.getElementById(‘inputbox’); gets the element id of the input text box having the id “inputbox”, and it stored that element id in the inputObject variable.

var URL = “serverSide.php” + “?name=” + inputObject.value;  This is the url which will be passed as a paramter to the ajaxObj.open() method. It is the url of the file to which the “XMLHttpRequest” object (ajaxObj) will send the request along with the parameters. Here “serverSide.php” is the name of the php file which will handle the request. “?name=” + inputObject.value part uses “GET” method to send the parameters to the server (the serverSide.php file). “?” indicates that the characters to follow are the parameters to be sent. “name” is the keyname of the $_GET[] request which will be received at the server’s end. “inputObject.value” is the value of the text input box whose element id was assigned to “inputObject” variable.

ajaxObj.open(“GET”, URL, true);

 

The above line of code opens a link to the server and sends the invisible request. The first parameter determines which method will be used to send the data to the server. In this case “GET” method is used since it is the easiest one. Other popular method is the “POST” method which is mainly used in situations where relatively large data is to be sent to the server which cannot be handled by the “GET” method. The second parameter is the URL of the file on the server side which will handle the request. This URL may also contain additional parameters in case “GET” method is selected as it is the case in this example. If it the “POST” is selected, it will usually have the path to the server file only. The third parameter determines if the data is to be sent “Asynchronously” or not. “Asynchronously” means that the “XMLHttpRequest” object will not wait for other Ajax calls to be finished/aborted, rather it will send the request in parallel with them. It is always set to true – that is where the name “Ajax” comes from. There are also fourth and fifth optional parameters “username” and “password”. This “username” and “password” pair is for a file which is password protected. It is generally not used at all.

ajaxObj.onreadystatechange = handleResponse;

 

This line tells the object what do if there is any change in the current state of the “XMLHttpRequest” object. As mentioned earlier, “XMLHttpRequest” object have five states from 0 to 4. If there is a change in these states from 0 to 4, the “handleResponse” function will be called.

“ajaxObj.onreadystatechange” As it name indicates if there is any change in the ready or initial state of the object then execute the function next to it. By the use of this statement we will then be able to process the server’s response.

ajaxObj.send(null);

 

If the “POST” method has been selected as the method of sendind data to the server, then it may contain the additional parameters to be sent the server. In this case, since the “GET” method is selected, the “send()” function is passed a “null” parameter.

// function called when there is a change ajaxObj state

function handleResponse()

{

// check if the request is complete

if (ajaxObj.readyState == 4)

{

// continue if the response is healthy

if (ajaxObj.status == 200)

{………

 

“handleResponse()” is the name of the function to be called when the “ajaxObj.onreadystatechange” directs it to do so. In other words, if there is a change in the current state of the ajaxObj. (Note that “XMLHttpRequest” object and the ajaxObj are used interchangeably in this article which is specific for this example only.)

   if (ajaxObj.readyState == 4)

{

// continue if the response is healthy

if (ajaxObj.status == 200)

{………

 

So if the readyState is 4 which means that the request sent to the server has been fully processed by the server and has sent back a response, we can continue. The ajaxObj.status returns the HTTP status code of the ajaxObj. The “XMLHttpRequest” object can have the following HTTP status codes:

200   OK

201   Created

204   No Content

205   Reset Content

206   Partial Content

400   Bad Request

401   Unauthorized

403   Forbidden

404   Not Found

405   Method Not Allowed

 406   Not Acceptable

407   Proxy Authentication Required

408   Request Timeout

411   Length Required

413   Requested Entity Too Large

414   Requested URL Too Long

415   Unsupported Media Type

500   Internal Server Error

501  Not Implemented

502   Bad Gateway

503   Service Unavailable

504   Gateway Timeout

505   HTTP Version Not Supported

 

of which the status code of ‘200’ is mostly used for practical purposes.

ajaxObj.status == 200

So we will continue if the status code is 200 which means that the HTTP response was valid without any network intereption.

 // store the server’s text response

var textResponse = ajaxObj.responseText;

// get control of the “display” div

var displayObj = document.getElementById(“display”);

// display the message in the div

displayObj.innerHTML = textResponse;

 

var textResponse = ajaxObj.responseText; causes the text response from the server to be stored in a variable. ajaxObj.responseText returns the reponse of the server in a text format. We can also have the response in XML like ajaxObj.responseXML which we will also look at the end of this article. var displayObj = document.getElementById(“display”); gets the element id of the DIV having the id ‘display’.

displayObj.innerHTML = textResponse; causes the text response from the server to be displayed as an HTML in the DIV having id ‘display’. The displayObj.innerHTML gives you read/write access to the inner HTML of the DIV.

Also note that in the HTML document the “Check Name” button has the following code:

 <input type=”button” name=”submit” value=”Check Name” onclick=”checkName();”/>

 

Notice onclick=”checkName();” which cause to call the checkName() function whenever this button is pressed/clicked.

Let’s now move to the server side – serverSide.php file code:

<?php

if (trim($_GET[‘name’]) == “”)

{

echo “No name specified.”;

}

else

{

$name = $_GET[‘name’];

if ($name == ‘John’ || $name == ‘Bill’ || $name == ‘Ted’)

{

echo “The name ‘”. $name .”‘ was found in our database.”;

}

else

{

echo “The name ‘”. $name .”‘ does not exist in our database.”;

}

}

?>

 

Again it is assumed that you know the basics of PHP.

The file serverSide.php is actually the file residing on the server side which deals with the request sent via Ajax.

   if (trim($_GET[‘name’]) == “”)

{

echo “No name specified.”;

}

else….

 

All the data sent via the GET method is stored in the $_GET[] global array. The name of the parameter sent via the GET method, like ‘name’ in this case, becomes a keyname of the $_GET[] array and its value is assigned to that keyname. So here  $_GET[‘name’] will return the value of the ‘name’ parameter sent from the client side.

For your reference:

var URL = “serverSide.php” + “?name=” + inputObject.value;

 

Notice the “?name=”, this is the name of the parameter sent and the value assigned to it by the “=” button becomes the value in  $_GET[‘name’].

Returning to the above code, it checks if the data sent by the client side (the value of the input text box) is empty, then it displays the appropriate message.

If the above check fails the following statements are executed.

 $name = $_GET[‘name’];

 

The value is assigned to a variable.

             

 if ($name == ‘John’ || $name == ‘Bill’ || $name == ‘Ted’)

{

echo “The name ‘”. $name .”‘ was found in our database.”;

}

else

{

echo “The name ‘”. $name .”‘ does not exist in our database.”;

}

 

Then that value is checked against the three names and the appropriate message is sent back to server.

This is how you can communicate with the server without any visible refresh using Ajax.

Let’s now also look at how to send data using the POST method and to receive it in an XML format. Almost all of the code will be the same except for the bolded parts below.

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml”>

<head>

<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />

<title>Simple Ajax Example</title>

<script type=”text/javascript” language=”javascript”>

function getXMLHttpRequestObject()

{

// initially set the object to false

var XMLHttpRequestObject = false;

if (window.XMLHttpRequest)

{

// check for Safari, Mozilla, Opera…

XMLHttpRequestObject = new XMLHttpRequest();

}

else if (window.ActiveXObject)

{

// check for Internet Explorer

XMLHttpRequestObject = new ActiveXObject(“Microsoft.XMLHTTP”);

}

if (!XMLHttpRequestObject)

{

alert(“Your browser does not support Ajax.”);

// return false in case of failure

return false;

}

// return the object in case of success

return XMLHttpRequestObject;

}

// get the XMLHttpRequestObject and store it in a variable

var ajaxObj = getXMLHttpRequestObject();

// function called when Check Name button is pressed

function checkName()

{

// continue if the ajaxObj object exists

if(ajaxObj)

{

// continue if the object is idle

if (ajaxObj.readyState == 4 || ajaxObj.readyState == 0)

{

// refer to the input text field

var inputObject = document.getElementById(‘inputbox’);

                         // request URL

                         var URL = “serverSide2.php”;

// open connection and send “GET” request to server

             ajaxObj.open(“POST”, URL, true);

                         // send the appropriate headers

                         ajaxObj.setRequestHeader(“Content-Type”, “application/x-www-form-urlencoded”);

// set the function to be called on a change in ajaxObj state

ajaxObj.onreadystatechange = handleResponse;

// set additional parameters (to be sent to server) to null

ajaxObj.send(“name=” + inputObject.value);

}

}

}

// function called when there is a change ajaxObj state

function handleResponse()

{

// check if the request is complete

if (ajaxObj.readyState == 4)

{

// continue if the response is healthy

if (ajaxObj.status == 200)

{

 // store the server’s XML response

                          var XMLResponse = ajaxObj.responseXML;

                          // get control of the “display” div

                          var displayObj = document.getElementById(“display”);

                          // work with the xml response

                          var responses = XMLResponse.getElementsByTagName(‘res’);

                          // clear the previous output

                          displayObj.innerHTML = “”;

                          // loop through the result

                          for (var i = 0; i < responses.length; i++)

                          {

                                      var response = responses[i].firstChild.data;

                                      // display the messages in the div

                              displayObj.innerHTML += response + ‘<br>’;

                          }

}

}

}

</script>

</head>

<body>

<p>Enter Name:

<input type=”text” id=”inputbox” />

</p>

<p>

<input type=”button” name=”submit” value=”Check Name” onclick=”checkName();”/>

</p>

<div id=”display”></div>

</body>

</html>

 

Copy the above code and put it in an html file, say “test2.html”. Let’s now move to the server side code:

<?php

 

   if (trim($_POST[‘name’]) == “”)

   {

               $response1 = “No name specified.”;

   }

   else

   {

             $name = $_POST[‘name’];

             

             if ($name == ‘John’ || $name == ‘Bill’ || $name == ‘Ted’)

             {

                         $response1 =  “The name ‘”. $name .”‘ was found in our database.”;

             }

             else

             {

                         $response1 = “The name ‘”. $name .”‘ does not exist in our database.”;

             }

             

   }

             

   $response2 = “The available names are John, Bill, and Ted”;

  

   header(“Content-type: text/xml”);

  

   echo “<?xml version=”1.0″?>”;

   echo “<responses>”;

   echo “<res>”.$response1.”</res>”;

   echo “<res>”.$response2.”</res>”;

   echo “</responses>”;

  

?>

Copy the above code and put it in a file, name it “serverSide2.php”.  Now let’s look into the changes from the previous example.

// request URL

var URL = “serverSide2.php”;

// open connection and send “GET” request to server

ajaxObj.open(“POST”, URL, true);

// send the appropriate headers

ajaxObj.setRequestHeader(“Content-Type”, “application/x-www-form-urlencoded”);

// set the function to be called on a change in ajaxObj state

ajaxObj.onreadystatechange = handleResponse;

// set additional parameters (to be sent to server) to null

ajaxObj.send(“name=” + inputObject.value);

 

The server side file name is changed to serverSide2.php. Note that there are no additional parameters with the file name.

ajaxObj.open(“POST”, URL, true); note that the send request method is now set to “POST”

ajaxObj.setRequestHeader(“Content-Type”, “application/x-www-form-urlencoded”); causes to send the appropriate headers sent during the normal POST method request.

ajaxObj.send(“name=” + inputObject.value); are the POST method parameters.

        // store the server’s XML response

        var XMLResponse = ajaxObj.responseXML;

// get control of the “display” div

var displayObj = document.getElementById(“display”);

       // work with the xml response

      var responses = XMLResponse.getElementsByTagName(‘res’);

       // clear the previous output

       displayObj.innerHTML = “”;

       // loop through the result

      for (var i = 0; i < responses.length; i++)

     {

         var response = responses[i].firstChild.data;

         // display the messages in the div

        displayObj.innerHTML += response + ‘<br>’;

      }

 

The above code handles the XML response sent by the server. Again it is assumed that you have basic understanding of XML and its structure.

var XMLResponse = ajaxObj.responseXML; gets the XML response returned by the server.

var responses = XMLResponse.getElementsByTagName(‘res’); like elements can be accessed by their IDs, they can also be accessed by their tag names. The tag to be accessed in this case is “res” which contains our desired response/text (You can refer to serverSide2.php code).

      for (var i = 0; i < responses.length; i++)

     {

         var response = responses[i].firstChild.data;

         // display the messages in the div

        displayObj.innerHTML += response + ‘<br>’;

      }

 

The above loop iterates as many times as there are items/elements in the “res” tags.

var response = responses[i].firstChild.data; Every item is treated as a child node in JavaScript and its data is accessed by  item.firstChild.data.

This data is then displayed by the display DIV.

Lastly the serverSide2.php file code:

<?php

 

   if (trim($_POST[‘name’]) == “”)

   {

               $response1 = “No name specified.”;

   }

   else

   {

             $name = $_POST[‘name’];

             

             if ($name == ‘John’ || $name == ‘Bill’ || $name == ‘Ted’)

             {

                         $response1 =  “The name ‘”. $name .”‘ was found in our database.”;

             }

             else

             {

                         $response1 = “The name ‘”. $name .”‘ does not exist in our database.”;

             }

             

   }

             

   $response2 = “The available names are John, Bill, and Ted”;

  

   header(“Content-type: text/xml”);

  

   echo “<?xml version=”1.0″?>”;

   echo “<responses>”;

   echo “<res>”.$response1.”</res>”;

   echo “<res>”.$response2.”</res>”;

   echo “</responses>”;

  

?>

 

Everything is almost the same as before and needs no further explanation except:

   header(“Content-type: text/xml”);

  

   echo “<?xml version=”1.0″?>”;

   echo “<responses>”;

   echo “<res>”.$response1.”</res>”;

   echo “<res>”.$response2.”</res>”;

   echo “</responses>”;

 

header(“Content-type: text/xml”); sends XML headers to the browser so the browser treats the text following this header as XML.

echo “<?xml version=”1.0″?>”; every XML document starts with this syntax just as the HTML document starts with its own headers.

   echo “<responses>”;

   echo “<res>”.$response1.”</res>”;

   echo “<res>”.$response2.”</res>”;

   echo “</responses>”;

 

Every XML document has one document element that contains all other elements. In this case “responses” enclosed between the braces is the document element. All other elements are placed in it (between its starting and ending tags).

echo “<res>”.$response1.”</res>”; one element of the document element. It contains our text/message which is then accessed by the client side, using JavaScript, as explained earlier.

Visit the Bookstore
The purpose of this article is to help you become familiar with Ajax, and how it sends and receives data without a visible refresh.  More advanced concepts are not treated here.

Tags:
Previous Post
HTTPS
Security

All About the SSL Protocol

Next Post
Computer Training
Certification

Five Technical Certifications To Grow Or Keep Your Job

Comments

  1. Reply

    Nice tutorial. A while ago, I wrote a tutorial on ajax too.

    • Pedro
    • December 29, 2008
    Reply

    Great very simple and powerfull at the same time, gave me a great idea which was to do with selecting different option boxes after the user entered a code without altering the forms value. then posting ….

    Thanks alot

    • Swapnil Merchant
    • April 2, 2009
    Reply

    Great work Sir, Very easy to understand and excellent flow of idea.
    Thanks a lot.

    • shashidhar
    • April 13, 2012
    Reply

    thank you for explanation sir ………

    • TiffanyKe
    • January 14, 2013
    Reply

    I have never tried anything with Ajax before but I think with this tutorial I can make it work. Thanks for the in depth text and code

Leave a Reply

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