Welcome to S-Design
The home of your bespoke, professional, fast-loading, interactive, database-driven web presence.
Menu
JAVASCRIPT TUTORIALS


JAVASCRIPT Ajax

AJAX is term used to describe Asyncronous JavaScript And XML. However, AJAX can be Asyncronous JavaScript... and Text, or HTML, or PHP or any number of other things. You don't have to use XML!
AJAX is used to send or retrieve data to/from the server without having to load/unload a webpage. If you've ever clicked a button and seen a small part of the page change, without the whole page unloading, and then reloading... then without doubt that was performed using JavaScript. And if the part of the page that changed included data that could only have come from the server, then it was most probably fetched using AJAX!

So, how do you use AJAX? We're going to create 3 JavaScript functions:
AjaxSend to SEND an AJAX request to the server.
AjaxReceive to RECEIVE the response from the server.
AjaxError to deal with any errors.
We'll also need a basic HTML & PHP page for testing purposes.

AjaxSend, AjaxReceive & AjaxError, saved as ajax.js var ajx;
function AjaxSend(data,page,p){
if(!ajx){
try{ajx=new XMLHttpRequest();}
catch(e){try{ajx=new ActiveXObject('Msxml2.XMLHTTP');}
catch(e){try{ajx=new ActiveXObject('Microsoft.XMLHTTP');}
catch(E){ajx=false; AjaxError('No Ajax Connection Available!');}
}
}
}
if(!p){
ajx.open('GET','http://www.mywebsite.com/'+page+'.php?'+data,true);
ajx.onreadystatechange=function(){AjaxReceive();};
ajx.send(null);
}
else{
ajx.open('POST','http://www.mywebsite.com/'+page+'.php',true);
ajx.onreadystatechange=function(){AjaxReceive();};
ajx.setRequestHeader('Content-Type','application/x-www-form-URLencoded');
ajx.send(data);
}
}

function AjaxReceive(){
if(ajx.readyState==4){
if(ajx.status==200){
ajxresult=ajx.responseText.split('|');
if(ajxresult[0]=='x'){eval(ajxresult[1]);}
else{AjaxError(ajx.responseText);}
ajxresult='';
}
}
}

function AjaxError(error){
alert('Ajax Error:\n\n'+error);
}

ajax.html <html>
<head>
<title></title>
<script type="text/javascript" src="http://www.mywebsite.com/ajax.js"></script>
</head>
<body>
<div id="ajax">
</div>
<a href="#" onclick="AjaxSend('do=test','ajax',false);return false;">Send Ajax Request</a>
</body>
</html>

ajax.php <?PHP
if($_GET['do']=="test"){
echo "x|document.getElementById('ajax').innerHTML='This text came from a PHP script on the server!';";
}
?>

Let's explain how all of the above works.

When you click the link "Send Ajax Request", the AjaxSend function is called, and passed 3 pieces of information:
[1] The data to send to the server.
[2] The page on the server to send the data to.
[3] Whether to send it via POST or not.

The AjaxSend function then creates an Ajax Object (XMLHttpRequest) and stores it in a variable called ajx. The scripts first checks to see if we already have an AJAX Object stored in ajx and doesn't create another if so... as we reuse our AJAX Object instead of creating a new one for every AJAX request.
It then checks to see if we want a GET or POST request to be sent, and opens the appropriate connection to the page we told it to send to.
It then sets-up a function to call when the response from the server changes... in this case AjaxReceive
It then sends the request (to ajax.php), together with any data we sent it.

The server (ajax.php) receives our request, and checks to see if we sent it a variable called do via GET, and that it equals "test".
If it does, then it sends a text string back to the AjaxSend function.
If it doesn't, then it sends back nothing to the AjaxSend function.

When the AjaxSend function receives a response from the server, it automatically fires the AjaxReceive function that was previously set up to handle responses.

The AjaxReceive function first checks whether the response is final (readyState==4 & status==200), and then splits the response into an array using the pipe character (|) as a split point.
It then checks to see if the first item in this array equals "x", and if so, passes the second item in the array to the JavaScript Eval() function, which allows the server response to execute JavaScript code.
If the first item in the array doesn't equal "x" (usually when the server generated any error, or sent nothing back at all), then it sends whatever the response was to the AjaxError function which will display it in an alert so you can see what happened!

If all goes well and the first item in the array did equal "x, then the text sent from the server will be evaluated... so "document.getElementById('ajax').innerHTML='This text came from a PHP script on the server!';" will be executed and the text "This text came from a PHP script on the server" will appear on the webpage inside the div with id="ajax"!

Title