It’s been some time already that I wanted to know “How the f*ck does theses AJAX thing works”.. Today I’ve tried some tiny things in AJAX and was suprise of the simplicity of all that stuff. I’ll describe in little piece of code what I achieve and how, in case of anyone of you might be interested 😉
So what I wanted, is to have a static xhtml web page, which I could load instantly and then change some content into this page without the need to reload it. -> AJAX baby.
I’ve added this <div> into a single web page together with the reference of my .js file between the <head> tags. I’ve also put a button to launch the javascript function when needed…
<head><script type="text/javascript" src="js/ajax.js"></script></head>
<body>
<div id="ajaxdiv"></div>
<input value="Load datas..." type="submit" onclick="ajaxFunction();">
</body>
Then, I’ve created the so-called js/ajax.js file with following code:
function ajaxFunction() {
var xmlhttp;
document.getElementById("ajaxdiv").innerHTML = "<p>Fetching datas...</p>";
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert("Your browser does not support XMLHTTP!");
return false;
}
xmlhttp.onreadystatechange=function() {
if(xmlhttp.readyState==4) {
// Get data from the server's response
document.getElementById("ajaxdiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","datas.php",true);
xmlhttp.send(null);
return true;
}
A little explanation: AJAX is making its stuff by dealing with XMLRequests, with all recent (who says decent ?) browsers, we could use the XMLHttpRequest, except that IE6 and IE5 is using ActiveXObject… So the 3/4 of this function is simply handling this case.
The rest of the function is pretty straightforward:
We declare the variable which we will use to store the XML request:
var xmlhttp;
We put inside our <div> to modify, a “please wait” message to show that we have launched the javascript function:
document.getElementById(“ajaxdiv”).innerHTML = “<p>Fetching datas…</p>”;
We declare the callback for the xml request: When we will launch the request, once its finished, this function will be called.
xmlhttp.onreadystatechange=function()
Inside this function, we simply take the result from the XML Request and assign it to our <div> …
document.getElementById(“ajaxdiv”).innerHTML=xmlhttp.responseText;
Last but not least, we send the request to the page we want to get the datas from:
xmlhttp.open(“GET”,”datas.php”,true); xmlhttp.send(null);
The datas.php is a very simple php page that make a sleep(2) and then echo something, to again demonstrate the loading of some datas…