|
AJAX For Dummies
Before reading this tutorial, you must have intermediate to advancded knowledge of JavaScript and HTML, knowledge of GET and POST form methods(wouldn't be much point if you didn't), and prefierably a basic idea of PHP so you know what happens to the GET and POST data after submission of a form.
Apparently, AJAX isn’t covered well enough so I decided to write a whole tutorial to explain it to you guys. Anyway, let’s begin. AJAX is really used to read XML pages using JavaScript but a lot of people use it to make requests to new pages to either send or gather information.
So first we will need our request object. The object we will be using for our request. It’s pretty simple but I must warn you, IE and FF interrupt this one differently. So let’s do a check to see which one the browser will support:
<script type="text/javascript"> <!— if(window.ActiveXObject){ var newrequest = new ActiveXObject("Microsoft.XMLHTTP"); } else { var newrequest = new XMLHttpRequest(); } //--> </script>
Okay so basically we use newrequest as our request object. The first check checks to see if there is an Active X Object which is supported by Microsoft. If so, it will return an active object that we can use for our request. The else is there for other browsers that don’t support the Active X Object and we use the XMLHttpRequest object for them. Okay so now it’s time to put our object to work.
So let’s add a function for this:
<script type="text/javascript"> <!— if(window.ActiveXObject){ var newrequest = new ActiveXObject("Microsoft.XMLHTTP"); } else { var newrequest = new XMLHttpRequest(); } function exeRequest(){ newrequest.onreadystatechange = grabJaxData; newrequest.open("GET","http://www.whatever.com/fads.php",true); newrequest.send(''); } //--> </script>
So we added a function to begin the whole process of AJAX. First things first. We add the onreadystatechange event handler to our request. This is to execute a function when the request changes state. Then we use open. First parameter is the method you want to use to on your request. Most of the time it will be GET. I recommend using GET when retrieving data or sending form data via the GET form method. In this request we will be sending no data so no worries. The second parameter is the page we want to work with. I just made up a url. And our final parameter doesn’t really concern you much, it’s just a Boolean type(true or false), leave it as true when wanting it to be asynchronous which is just about always. Now to send our data. If you have data to send using the GET Method, add it to the url you are opeing by adding it to the url by doing:
?name=value&name=value etc.
Name being the name of the form element and value being the value of it. The last line is for POST Data only but must included for our AJAX to execute correctly. Since we have no POST Data to send we send an empty string. Then could also be sent as null but must be one or the other for cross browser reasons.
Now for the next function. Remember how I used the onreadystatechange as an event handler on our request object? Good, you should. Now we are going to execute a function with it.
<script type="text/javascript"> <!— if(window.ActiveXObject){ var newrequest = new ActiveXObject("Microsoft.XMLHTTP"); } else { var newrequest = new XMLHttpRequest(); } function exeRequest(){ newrequest.onreadystatechange = grabJaxData; newrequest.open("GET","http://www.whatever.com/fads.php",true); newrequest.send(''); } function grabJaxData(){ if(newrequest.readyState == 4 && newrequest.status == 200){ var addedjax = newrequest.responseText; alert(addedjax); }} exeRequest(); //--> </script>
This function is pretty easy to understand. The first if statement pretty much checks if the script is ready to be loaded and it’s okay to be executed. If it is it will return what is called responseText. ResponseText basically contains the HTML of that page or XML if it’s an XML page. If it’s an XML page, then it will also return responseXML which we can use XML DOM on to get the information we desire.
So what can I do with the responseText? This is where we can stick it in a place holder to work as a element containing normal HTML. So let’s create a div using createElement() and stick the responseText in as its’ innerHTML.
function grabJaxData(){ if(newrequest.readyState == 4 && newrequest.status == 200){ var addedjax = newrequest.responseText; var jaxhold = document.createElement(‘div’); jaxhold.innerHTML = addedjax; }}
Pretty much the same as before except much more useful. Why? Because now we can use jaxhold as a normal div with our AJAX in it and grab elements as we always would. So let’s try it:
alert(jaxhold.firstChild.nodeName);
That will alert the nodeName of the firstChild of our div. Will be TITLE pending the browser.
So we covered just about everything you can do with the GET method in AJAX. Now time for sending data with the POST method. Pretty simple stuff.
<script type="text/javascript"> <!— if(window.ActiveXObject){ var newrequest = new ActiveXObject("Microsoft.XMLHTTP"); } else { var newrequest = new XMLHttpRequest(); } function exeRequest(){ newrequest.open("POST","http://www.whatever.com/fads.php",true); secondrequest.setRequestHeader("Content-type","application/x-www-form-urlencoded"); newrequest.send('name=value&name=value'); } exeRequest(); //--> </script> A bit different. We open the page the same way except we declare our form method as post. A new line must be added.
secondrequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");
That’s pretty much just there to let the request know we’re going to be sending POST data and as far as I can see it is required. And the final line is the sending of the POST data. We send the data the same way as we would in the GET method with name=value and all except we use the send method to send the POST data this time. You may have noticed onreadystatechange was never declared. This is because we weren’t changing pages or reading information so I saw no purpose to it. You may use it though and it’s the same as with the GET method for the most part. Anyway, that’s my AJAX tutorial. Practice makes perfect. And finally, I plan on showing you how to interact with XML pages next.
|
Greg says: Coding music... Greg says: Hmm... Greg says: I wouldn't rule it out. Chris 3.0 [New features? Yes.] says:
Greg says: If you think about machine code it's a bunch of 1s and 0s Chris 3.0 [New features? Yes.] says: Anything is possible. Greg says: Yeah try to code Metallica Chris 3.0 [New features? Yes.] says: Yeah, I'll get right on that... right after I learn to fly.
|
|
|
|
great tutorial!!...but what if we still dont understand it?...lol
i guess im dummer than a dummy=P
|
|
|
|
Thanks, this is perfect for me moose
|
|
|
|
|
great tutorial!!...but what if we still dont understand it?...lol i guess im dummer than a dummy=P What don't you understand?
|
Greg says: Coding music... Greg says: Hmm... Greg says: I wouldn't rule it out. Chris 3.0 [New features? Yes.] says:
Greg says: If you think about machine code it's a bunch of 1s and 0s Chris 3.0 [New features? Yes.] says: Anything is possible. Greg says: Yeah try to code Metallica Chris 3.0 [New features? Yes.] says: Yeah, I'll get right on that... right after I learn to fly.
|
|
|
|
everything...although, that might be becuase i have no idea what POST and GET are...plus i dont know PHP at all....and it prolly doesnt help that im a JS noob too =/
Ive read alot of tutorials on AJAX...but all that happens is i get more confused...i donno why =(
|
|
|
|
Real AJAX helps to have a knowledge of XML too (XML just helps in general actually).
$_POST and $_GET are global variables in PHP (either after v3 or v4). POST and GET are the two (and only to my knowledge) methods for submitting a form. GET submits the data via the URL where its public, and POST just submits the data.
For example, if I was using PHP for this page I could get quite a bit of data (the comments show what the output would be).
echo $_GET["board"]; // codetuts echo $_GET["action"]; // display echo $_GET["thread"]; // 115444875
POST is usually used for submitting data and GET is for visiting different pages (to my knowledge anyway).
|
|
|
|
|
I suggest running a more secure check.
var httpRequest; if(window.ActiveXObject) { httpRequest = new ActiveXObject("Microsoft.XMLHTTP"); } else if(window.XMLHttpRequest) { httpRequest = new XMLHttpRequest(); } if(httpRequest) { // RUN CODE }
|
|
|
|
Aaron, why not just add another if and return false? It'd just save time if you like to space, otherwise your idea should work fine though.
if(window.ActiveXObject) { var httpRequest = new ActiveXObject("Microsoft.XMLHTTP"); } else if(window.XMLHttpRequest) { var httpRequest = new XMLHttpRequest(); } else { return false; }
|
|
|
|
|
That depends on how you go about executing the code. Whether you declare the object within the function or run the function after (though the first is preferable).
Last Edit: Aug 1, 2006 20:36:38 GMT by Aaron
|
|
|
|
Yeah, I realized that could be an issue the second I saw you had replied. I tend to use functions if I use AJAX or make an AJAX object. Not sure why, I just do.
|
|
|
|
|
I don't use AJAX much. I do however plan to for my website's resources. Where it searches an XML document for the script when a link is clicked and opens it in a blank window. I figure it 'll save me some time and space in the future.
|
|
|
|
|
Most browsers should probably support the request, didn't really think about it but most people probably don't have a browser anyway. What is the point of having data on an XML page when you can just have a mySQL database or a txt file you can pull from and insert, edit, and delete that information? There is also REQUEST. It handles both POST and GET methods. It also has $_COOKIE in it. I could also get into $_GLOBALS and $_SERVER and $_FILES. But I was being relevent to his question.
|
|
|
|
|
Would the activeXobject also work like this. try { xmlHttp = new XmlHttpRequest(); } catch(e) { //if it fails, we'll try toput a request in it for internet explore try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { //if it fails again, we'll try to put a request in it for IE 5+ try { xmlHttp =new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) { //if it fails again, we'll alert the user that his browser doesn't support AJAX document.write("Your browser doesn't support AJAX!"); } } }
Last Edit: Sept 15, 2007 20:58:43 GMT by blu
|
|
|
|
Besides an "ALERT is not defined" error, it looks good. There's many different ways to do it.
|
|
|
|