December 20 th

8

Beginners AJAX Tutorial Series Part 4

Posted by Andy Bailey
3,569 views

Ajax Avenue Street Sign

This is part 4 of the AJAX Tutorial Series.
You can see the other Beginners AJAX Tutorials here.

In this part of the tutorial series we will get ready to rumble! download data using the object we created in the last part...

onreadystatechange

What the hell is that? lol, it's not move states when you're ready.. it's what we use on the object we created to see what state it is in, the different states are:

  • 0 - Uninitialized
  • 1 - Loading
  • 2 - Loaded
  • 3 - Interactive
  • 4 - Complete

We can check for an objects state to see where it's at to decide if we can output the result or not, we can combine this with a test for the HTTP status of a download to see if it was successful, we can check for a value of 200 which means everything went ok. (a value of 404 would mean file not found just like normal HTTP status codes).

To use the readystate property, just bang it on the end of the object name and put that in an 'if' statement. Ie...

if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200)
{do something}

(the && means AND, so we check the readystate AND the status, if they are BOTH correct then execute the code in the curly brackets)

To put that in the code of the last tutorial, replace the bit that outputs the message about the oranges box being collected with an anonymous function that is attached to the objects readystate. It's not named an anonymous function because it has a secret identity, it is just a nice way of running a function with no name when a certain thing happens like the objects' readystate being changed.

For example, if we put
XMLHttpReqestObject.onreadystatechange = function()
{
do something
}

We have attached the onreadystatechange to the object we created, as soon as that objects readystate has altered, the anonymous function takes action and executes the commands contained in the curly brackets ({do something }).

That's exactly where we put the test to see what the HTTP status and readystate number is. Ie.

XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200)
{
data downloaded, do something with it...
}
}

You may have noticed little graphics that are synonymous with web 2.0 and AJAX ( ajax loading ). You can add one of those to let the user see something is happening. In the code above, you can check for a readyState of 1 (loading) and add some text like this:

XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 1)
{
obj.innerHtml="Loading...";
}

if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200)
{
data downloaded, do something with it...
}
}

The FiddyP amazing analogy:
Last time we had created a box for the oranges that we want from the AJAX shop
XMLHttpRequestObject = new XMLHttpRequest();
then we opened it and sent it to the AJAX shop with a label of what we want.
XMLHttpRequestObject.open("GET", dataSource);
And we wait for the signal that the box we sent was filled ok and ready to go
if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200)

Your whole code will now look like this...

HTML:
  1.   <head>
  2.     <title>FiddyP AJAX Tutorial Series Part 4</title>
  3.     <script language = "javascript">
  4.       var XMLHttpRequestObject = false;
  5.       if (window.XMLHttpRequest) {
  6.         XMLHttpRequestObject = new XMLHttpRequest();
  7.       } else if (window.ActiveXObject) {
  8.         XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
  9.       }
  10.       function getData(dataSource, divID)
  11.       {
  12.         if(XMLHttpRequestObject) {
  13.           var obj = document.getElementById(divID);
  14.           XMLHttpRequestObject.open("GET", dataSource);
  15.  
  16.           XMLHttpRequestObject.onreadystatechange = function()
  17.           {
  18.             if (XMLHttpRequestObject.readyState == 4 &&
  19.               XMLHttpRequestObject.status == 200) {
  20.             }
  21.           }
  22.        obj.innerHTML = "Ready to download";
  23.            
  24.         }
  25.       }
  26.     </script>
  27.   </head>
  28.     <H1>Fetching data with Ajax</H1>
  29.     <form>
  30.       <input type = "button" value = "Display Message"
  31.         onclick = "getData('oranges.txt', 'targetDiv')">
  32.     </form>
  33.     <div id="targetDiv">
  34.       <p>The fetched data will go here.</p>
  35.     </div>
  36.   </body>
  37. </html>

OK, so you have your box at the AJAX shop full of oranges.txt, next tutorial we'll do something with the oranges...

If you've been following the other tutorials then the code above shouldn't be so hard to understand (shyeah right!), it's just a bit more added to what we've already covered. You can copy the code from above and try it out yourself or you can click here to see it in action (hold on to your hat :-P)

We're still in the AJAX starting blocks waiting for the bang to start us on the AJAX runway but don't despair, next tutorial we will actually download data from a server and display it on the page without a reload which is what AJAX is all about. Once we can actually display the data, we can start doing things with it and then we can start to make pretty little scripts that do amazing things like count the amount of times a pink box has been clicked. hehehe, we'll do more than that I promise!

Popularity: 9% [?]

Category : Code | ajax

Related Posts

  • Beginners AJAX Tutorial Part 2
  • Beginners AJAX Tutorial Series Part 5
  • Beginners AJAX Tutorial Series Part 3
  • Introducing AJAX CommentLuv
  • 3 day lazy period is due to finish. grr
  • Beginners AJAX. Tutorial series. Part 1
  • Spreading Coding luv

  • Comments

    witchypoo (43 comments.) December 20, 2007

    Andy, you are so generous to share this. I don’t want to hurt my brain, so I’m filing this away for when I really have to use it.

    witchypoo’s last blog post..Who is Ass Burger Boy?

    Andy Bailey December 20, 2007

    hehe, it should get more interesting from part 5. Thanks for your comment :-)

    Juned Kazi December 31, 2007

    I have just started with Ajax and urs was the first tutorial which I did.
    I found all the 4 tutorial very simple to understand and test it out.
    I hope to see some more tutorials from u.
    Thanks a lot for sharing all these stuff.

    Cheers

    Gtkmasters January 1, 2008

    I was very interested in learning how to program AJAX, but every tutorial I found, even from my most trusted websites, gave a whole concept that was so recondite and extremely confusing. When I found your tutorial I assumed that it was just another extremely confusing and worthless tutorial, but I was dead wrong. Your tutorials have helped me to understand it so much that I am going to begin using AJAX from now on with my PHP scripts. xD Thanks for explaining it on simple easy to read terms so I can finally understand AJAX. I will wait patiently for Part 5.

    Andy Bailey January 2, 2008

    juned: no problem! glad you liked it

    GTmasters: I am really happy you got something out of these tutorials, I’ll have part 5 up before the end of the weekend!

    Morten Ryum January 12, 2008

    You truely are awesome.
    thank_you for providing a tutorial that’s finally readable (all the others are basically a big chunk of plain text, lol)

    Andy Bailey January 12, 2008

    thanks Marten, I appreciate you letting me know! it always gives me inspiration to make another one..

    Bubbila March 29, 2008

    Sweet resource, just what I have been looking for.

    Leave a comment

    15 online now
    the most online was 176
    elottery Ajax commentluv
    Sponsors
    available ad space available ad space available ad space available ad space available ad space available ad space