Beginners AJAX Tutorial Series Part 5

Posted by Andy Bailey at 4 January, 2008, 12:17 pm

AJAX Avenue

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

Hurrah! this tutorial will actually download some data (yey!) We will use everything we have learned so far and add just a little bit that will allow us to download data from the server and put it somewhere on the page without a refresh. (I know, you must have goosebumps!) :-)

XMLHttpRequestObject.send(null);

We need this command to initiate the object send. We created an object, created a place for the data to go, we created a routine to wait patiently for the object to be ready and sent the object to the data source using the above command. The patient routine for the waiting will take the response to the data source and put it in the div we created in the HTML of the page.

We can replace the bit from the last bit of complete code (on part 4) with this command and instead of it saying it's ready to download, it will actually do the fetching for the obj.innerHTML=XMLHttpRequestObject.responseText; which is called when the readyState and Status are ok.

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

I'll try and make this code easier to understand with a picture using pretty colours! :-)
Part 5 AJAX picture

The blue bit gets called when the user clicks the button, if the object was successfully created then create a routine that 'listens' to the objects readyState and status. Then the XMLHttpRequestObject.send(null); command does the action and when that goes ahead and activates XMLHttpRequestObject.open("GET", dataSource); which goes off and gets the data pointed to by dataSource which of course changes the objects status and readyState. When it is at what we want, we inject the responseText to the div pointed to by divID.

Simple! :-/

You can see it in action here

Exciting huh? LOL . It'll display anything that is in the oranges.txt file, not much use yet but at least we know we can fetch data!

What if, instead of displaying the contents of a text file, we used a php script to 'echo' out something?.. replace oranges.txt with this code..

PHP:
  1. echo "these are some oranges created by php!";
  2. echo "<br/>ooooooooooooooooooooooooooooooooo";
  3. ?>

(don't forget to enclose any php script with <?php and ?> or it wont work - I cant put them in here otherwise it will run the script instead of showing the code. Also, change the onclick event in the html to call oranges.php (if you saved the php with that name) instead of oranges.txt

You can see that in action here

There may be a pause between you clicking and the message being displayed. We can let the user know that something is happening by adding another if condition to look for a readyState of 1 (loading) and displaying the message "off to get oranges..." like this..

HTML:
  1. if (XMLHttpRequestObject.readyState == 1)
  2. {
  3.     obj.innerHTML="off to get oranges...";
  4. }

we just chuck that into the anonymous function that is called when the readyState changes...

HTML:
  1. XMLHttpRequestObject.onreadystatechange = function()
  2.           {
  3.             if (XMLHttpRequestObject.readyState == 4 &&
  4.               XMLHttpRequestObject.status == 200) {
  5.         obj.innerHTML=XMLHttpRequestObject.responseText;
  6.  
  7.             }
  8.         if (XMLHttpRequestObject.readyState == 1)
  9.         {
  10.         obj.innerHTML="off to get oranges...";
  11.         }
  12.           }

See that in action here

You can download all the files used in this tutorial here.

Now we're getting somewhere! But, what if we want to send data to the php file so it can do something more than print a hardcoded message?
Actually, it's quite easy! come back next week to see the final part where we'll send something to the php file and have it send back something it made with what we sent. (it could be a username or contents of a text field - think form validation!)

You can subscribe to my feed with the button at the top right of this blog or add your email to the box on the sidebar of the main page to subscribe by email. I hope you can come back and learn a bit more, enough at least to make your own php script and AJAX page....

Popularity: 10% [?]

Category : Code | PHP | ajax

Related Posts

  • Beginners AJAX Tutorial Part 2
  • Beginners AJAX Tutorial Series Part 4
  • 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 (37 comments.) January 4, 2008

    I stumbled this. See if you can detect it with your whatchamacallit.

    witchypoo’s last blog post..Ask witchypoo: Purple Plates

    Andy Bailey January 4, 2008
    thanks witchypoo! it went up about 500 hits since you stumbled!
    Snowlark (8 comments.) January 4, 2008

    Good code - good tutorial!

    (i’ve been messing with AJAX on Rails lately)

    Snowlark’s last blog post..Staff IT Right in 2008

    Andy Bailey January 4, 2008
    thanks! actually, I’m learning as I teach. I’m still a beginner myself, each time I learn something new, I have enough for a new tutorial!
    Snowlark (8 comments.) January 4, 2008

    Everyone’s a beginner, truly. We’re all on the “bleeding edge” of all this technology. BUT, you’ve set yourself apart from the rest of us in that _YOU_ take the time to give back to all of us … hacks … through descriptive text and code snippets (clear snapshots and code examples too!). :)

    Tanx, Man!

    Snowlark’s last blog post..Staff IT Right in 2008

    chase (12 comments.) January 7, 2008

    I told my colleagues who want to learn ajax to check this tutorial. Happy new year btw and now I am back in the blogosphere!

    chase’s last blog post..Rewind, Recaps And The Lot Part 1

    David Anderson (2 comments.) January 7, 2008

    Thanks for having this tutorial in your blog. I’m looking for some tutorials for AJAX,
    glad that I came across with your blog. I’ll recommend this to some of my friends who are quiet interested to learn AJAX.

    Andy Bailey January 7, 2008
    Chase: welcome back! I hope you enjoyed your time away. thanks for the referrals!

    David: you’re welcome! bear in mind though that I am a beginner too, I’m just adding a new tutorial when I make or learn a new thing myself.

    AntiBarbie (40 comments.) January 7, 2008

    I just reviewed this on StumbleUpon too. I hope it gets you a few more views. Great series Andy. You shine as a teacher.

    AntiBarbie’s last blog post..Wondering about Working Girls

    Andy Bailey January 7, 2008
    thanks AntiB! It’ll climax (oo-er) with part 6 where we’ll make a Stumblebait page with AJAX..
    wow, I really must catch up on my dofollow comments. I’ve been sick :-(
    webringnet.com (1 comments.) January 8, 2008

    great tutorial. thanks for write it out. i know that ajax is essential now days, but just few people know how to program it.

    webringnet.com’s last blog post..Cool Gadgets Part 1

    Sharon (86 comments.) January 8, 2008

    Ouch, my head hurts. Even all the pretty nice colors didn’t help :)

    I’ve bookmarked it for when the time comes that my head comes out of cloud 9 because obviously this is something that I’ve been trying to learn….. And it looks like I can actually somehow understand it.

    Sharon’s last blog post..One Kiss Can Make A Difference

    Snowlark (8 comments.) January 8, 2008

    OK - Part 6 sounds like a winner, too! Can’t wait …

    Snowlark’s last blog post..Development Update ? Week 1 of 2008

    Andy Bailey January 8, 2008
    webring: it’s not that hard as it turns out, there are plenty of pre-made libraries that can take all the pain out of doing AJAX. stick around for after part 6 and I’ll show you some of the easier ones that can quickly create animated divs, reads and writes to databases etc.

    sharon: same as above for you too, stick around and you’ll see some even easier ways to use AJAX with libraries such as jquery and prototype.

    Snowlark: come to a blog near here soon!

    Prakash January 10, 2008

    Good start. It gave me a good idea to start learning Ajax but only the basics. If I get any help in creating Ajax based custom components, it will be helpful and apprecitable.

    Thanks

    Andy Bailey January 10, 2008
    Prakash: it’s just the basics I need to pass on, once you can handle them then it’s up to you to expand. I’m glad I could bring a little AJAX your way. I look forward to seeing what you come up with
    Eric "Speedcat Hollydale" (2 comments.) January 15, 2008

    Ummm, yes. I agree!!!!! Sorry, I am positively confused. I am still novice with code :(
    Eric “Speedcat Hollydale”’s last blog post..Corn Chips & Foreheads

    John (1 comments.) January 29, 2008

    Thanks very much for the tutorials. These were just what I needed and I look forward to any more you’re able to put together.

    Andy Bailey January 29, 2008
    John: thanks for taking the time to let me know you found it useful!

    Leave a comment

    7 online now
    the most online was 176
    elottery magnetic Sponsoring
    Sponsors
    available ad space available ad space available ad space available ad space available ad space available ad space