In this tutorial I will show you the really basic of AJAX and make a script that just returns the IP-address of the person viewing the site...
For those who didn't know, AJAX is done in JavaScript (or at least I've always done it there). I've made a function witch does make things a bit easier... Let's take a look at that one:
function getXHttpElement(){ var xmlHttp; try { xmlHttp=new XMLHttpRequest(); } catch (e) { try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("Your browser does not support AJAX!"); } } } return xmlHttp; }
Now this might look confusing, but all it does is to create a new AJAX object and return it. The complicated code is just because some browsers uses different methods, so this should work on most browsers... If it don't, JavaScript will alert the user.
Now what this does is as said just to return a AJAX object. It doesn't do anything more then that...
But we want it to do a little bit more so let's continue coding, shall we?
AJAX_object = getXHttpElement(); AJAX_object.onreadystatechange=function(){ switch(AJAX_object.readyState){ case 0: alert("State 0"); break; case 1: alert("State 1"); break; case 2: alert("State 2"); break; case 3: alert("State 3"); break; case 4: alert("State 4"); break; } }
Wow, wow, wow, you might say. That's an awful lot of code... I know it is but it's really simple... Here we create a AJAX-object named AJAX_object with the function we created... Then we say AJAX_object.onreadystatechange...
AJAX objects have so called readystates... This tells where in the process the object is... When you create a AJAX-object it enters state 1... This isn't something you need to remember but I thought I'd tell you... The only state you should care about is state 4. That's when AJAX has received the answer to the call to the server. So let's say we have a phpfile named getIp.php (this is really simple to create, the code is only:
<?php ?>
).
So we want to get the IP to the viewer... Well, to do that we simply change the state 4 to:
alert(AJAX_object.responseText);
Then we set up the AJAX-object to get ready to send with the code:
AJAX_object.open("GET","getIp.php",true);
This set's up the AJAX_object to send and receive data to/from getIp.php. Then we only need one command left and that is:
AJAX_object.send();
And that's it... HTH