AJAX Tutorial: In this post, We try to use Ajax in our simple application. First time, We will build simple ajax library. Then, we write page to load the ajax library. This is very basic application. You can still extend it for more complex web.
Ok, for this practice, we need 3 file (I create within www/test/ajax directory):
- ajax.js -> as ajax library
- test.php -> as main page
- home.html -> will be loaded as content
First, write below line codes within ajax.js
01 | function callAJAX(url, pageElement, callMessage) { |
02 | document.getElementById(pageElement).innerHTML = callMessage; |
04 | req = new XMLHttpRequest(); |
07 | req = new ActiveXObject( "Msxml2.XMLHTTP" ); |
11 | req = new ActiveXObject( "Microsoft.XMLHTTP" ); |
19 | req.onreadystatechange = function () {responseAJAX(pageElement);}; |
20 | req.open( "GET" ,url,true); |
25 | function responseAJAX(pageElement) { |
27 | if (req.readyState == 4) { |
28 | if (req.status == 200) { |
29 | output = req.responseText; |
30 | document.getElementById(pageElement).innerHTML = output; |
then, we create test.php, enter following codes:
03 | <SCRIPT language= "JavaScript" SRC= "ajax.js" ></SCRIPT> |
05 | <body onload= "callAJAX('home.html','displaydiv')" > |
09 | <td id= "displaydiv" ></td> |
last, we create home.html, enter following line code:
Now, point your browser to http://localhost/test/ajax/test.php, you will get like this:
