Quick and Dirty AJAX Tutorial - AJAX Basics
(Page 2 of 4 )
If you don't know what AJAX is, it's nothing new, just a buzzword for Asynchronous JavaScript and XML. I'm not gonna bother going into the history or great detail or anything, and if you really want to know, google it. We'll start off with one of the simplest examples possible, just to get your feet wet. We'll create 2 files, test.php (the page being updated), and ajax.php (the page retrieving the updates). Here's test.php:
<html> <head> <script type="text/javascript"> function createRequestObject() { var ro; var browser = navigator.appName; if(browser == 'Microsoft Internet Explorer') { ro = new ActiveXObject("Microsoft.XMLHTTP"); } else { ro = new XMLHttpRequest(); } return ro; } var http = createRequestObject();
function sndReq(action) { http.open('get', 'ajax.php'); http.onreadystatechange = handleResponse; http.send(null); }
function handleResponse() { if(http.readyState == 4) { var response = http.responseText; document.getElementById('foo').innerHTML = response; } } setInterval('sndReq()', 5000); </script> </head> <body> <div id="foo"> retrieving data... </div> </body> </html> |
In the above code we created 3 functions. createRequestObject() creates the appropriate object depending on whether you're using IE or not (cause we all know Microsoft has to be different), and then we assign the object to an http variable so it's easier to work with. Our next function, sndReq(), sends our request to ajax.php and retrieves the reponse (which will be whatever we instruct ajax.php to output). Our 3rd and final handleResponse() function, handles our response by updating the div "foo" with whatever data we got from the sndReq() function. The last line of code uses one of JavaScripts built-in functions, setInterval(), which is being instructed to execute our sndReq() function every 5 seconds.
Now onto ajax.php:
<?php echo 'hello world.'; ?> |
That's all there is to the basics of AJAX. Loading our test.php page, you should see the text "retrieving data..." for 5 seconds before it dynamically updates to "hello world."
Sure it's neat, but not really useful now is it? One problem is that our page is constantly being updated every 5 seconds with the same text; it would make a lot more sense to only update the page when the text changes (don't argue with me, it just would). If you try to alter the code to update multiple divs on the same page then you might run into another problem, which is conflicting data.
Next: A More Advanced Approach >>
More Miscellaneous Articles
More By notepad