Asynchronous Javascript And XML Example (AJAX)

This is a simple javascript AJAX tutorial using php, javascript and XMLHttpRequest. AJAX is the fundamental lynchpin of web 2 services and underpins almost every widget today. This is the simplest javascript example that demonstrates AJAX. No prior php knowledge required. Great for beginers to AJAX.

This example consists of two files. ajaxexample.html contains all the javascript and getresult.php is the php backend that returns an xml result. Create or copy these two files into the same directory on a webserver (such as apache) that supports php.

ajaxexample.html
 1. <html>
 2. <head>
 3. <script language="javascript">
 4. function new_XHR() {
 5.     var xhr;
 6.     try{
 7.         xhr = new ActiveXObject("Msxml2.XMLHTTP");
 8.     }catch(e){
 9.     try{
10.         xhr = new ActiveXObject("Microsoft.XMLHTTP");
11.         }catch(E){
12.             xhr = false;
13.         }
14.     }
15.     if(!xhr && typeof XMLHttpRequest != 'undefined'){
16.         xhr = new XMLHttpRequest();
17.     }
18.     return xhr;
19. }
20. 
21. var myxhr;
22. function DoAjaxCall(){
23.       myxhr = new_XHR();
24.       myxhr.onreadystatechange=MyAjaxCallback;
25.       myxhr.open('GET',"getresult.php?"
26.         +"name="+document.getElementById("NameBox").value);
27.       myxhr.send(null);
28.     }
29.        
30. function MyAjaxCallback(){
31.     var name;
32.     var message;
33.     if(myxhr.readyState==4 && myxhr.status==200){
34.         var subrootNode = myxhr.responseXML.getElementsByTagName('user-data');
35.         for(i = 0 ; i < subrootNode[0].childNodes.length ; i++){
36.             var node = subrootNode[0].childNodes[i];
37.             if(node.tagName=="name")
38.                 name=node.firstChild.nodeValue;
39.             else if(node.tagName=="message")
40.                 message=node.firstChild.nodeValue;
41.             else{}
42.         }
43.         document.getElementById("MessagePane").innerHTML = 
44.                                     "<b>"+name+" :</b> \""+message+"\""; 
45.     }
46. }
47. </script>
48. </head>
49. <body>
50. <form>
51. Name <input id="NameBox" type="text"/>
52. <a href="javascript:DoAjaxCall()">Send the data without submitting the form</a>
53. </form>
54. <div id="MessagePane"/>
55. </body>
56. </html>
Hide line numbers
Now type http://127.0.0.1/WEB/AJAXExample/ajaxexample.html in a browser, type your name in the textbox and click on the link.

lines 4-19 Creates an XMLHttpRequest object

lines 22-28 DoAjaxCall get's called when you click on the link. This creates an XMLHttpRequest object sets MyAjaxCallback as the callback function and adds the url to call.

lines 30-46 Once getresult.php is called the MyAjaxCallback function is called with the reuslt. You can then 'decode' the XMLHttpRequest object by traversing the sctructure and extracting the information.

getresutl.php
 1. <?php header('Content-type: text/xml');
 2.  
 3. $my_name = $_GET["name"];
 4. 
 5. $dom = new DomDocument('1.0');
 6. $dom->formatOutput = true;
 7. 
 8. $userdata = $dom->createElement( "user-data" );
 9. $dom->appendChild( $userdata );
10. 
11. $name = $dom->createElement("name");
12. $name->appendChild($dom->createTextNode("Doctor Octopus"));
13. $userdata->appendChild($name);
14. 
15. $mesg = $dom->createElement("message");
16. $mesg->appendChild($dom->createTextNode("Hello there $my_name, prepare to be mangled"));
17. $userdata->appendChild($mesg);
18. 
19. echo $dom->saveXml();
20. 
21. ?>
Hide line numbers
You can call this php script directly by typeing http://127.0.0.1/WEB/AJAXExample/getresult.php?name=sheena in your browser