December 11 th

18

Beginners AJAX Tutorial Series Part 3

Posted by Andy Bailey
2,509 views

Ajax Avenue Street Sign

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

In this part of the tutorial series we will open the object that you created in the last tutorial. So far, we have created an object to handle the data and made sure it is created in whatever browser you are using. Now, if we want to work with the created object, we need to open it...

Open The XMLHttpRequest Object

Opening the object prepares it for use to fetch the data from a server, the act of opening the object doesn't actually fetch any data yet.

The FiddyP amazing analogy :- Imagine you created a page to collect a box of oranges from the local AJAX fruit shop. In the last tutorial, you created the box (object), now you need to open it so the AJAX oranges can fit inside...

The open comand: [square brackets] = optional arguments.

open("method", "url" [, asyncFlag[, "username"[, "password"]]])

Explanation:

  • method is the HTTP method to use when opening the connection. It can be 'GET', 'POST', 'PUT' or 'HEAD'
  • url is the URL you want to download from
  • asyncFlag is a Boolean (one or the other) value used to indicate that the call is asynchronous. (no waiting for it to finish)
    This defaults to TRUE or 1 so is not needed unless you want to specify that the page waits for completion.
  • username is if you need a username to access the page identified by URL
  • password is for a password if it's required.

Make sense? lol, maybe not. Here's how it looks in use:

XMLHttpRequestObject.open("GET","oranges.txt");

We just add the open bit of code on to the end of the name of the object we created. Here's an example page where we create a form in HTML and add a button for the user to click to open a remote file on the server with AJAX. Because AJAX uses CSS to change elements of the page, we need to create a <div> on the page to show the data we retrieve from the remote file. We'll also have to create a function to take action when the button is clicked (we can't do it the normal way with the <form> action because that would cause the page to reload).

Here's the form and div html:

HTML:
  1.   <input type = "button" value = "Display Message" onclick = "getData('oranges.txt', 'targetDiv')">
  2. </form>
  3.  
  4. <div id="targetDiv">
  5.   <p>The oranges box will go here.</p>
  6. </div>

You can see that the button has an 'onclick' event. That's the javascript bit that calls the function when the button is clicked. The <div> has an id so the function will know where to put the collected data.

The javascript function is held in the <head> part of the document;

JAVASCRIPT:
  1. function getData(dataSource, divID)
  2.       {
  3.         if(XMLHttpRequestObject) {
  4.           var obj = document.getElementById(divID);
  5.           XMLHttpRequestObject.open("GET", dataSource);
  6.  
  7.           obj.innerHTML="Oranges Box Opened!";
  8.         }
  9.       }

The function is called with the name of the data file we want (dataSource) and where to put the output (divID)
The first line checks if the XMLHttpRequestObject was created (we did that last time so you know it should get to this point)
If it finds that the object was created, it moves on to set the variable obj to the <div> we created by using getElementByID
Next, we use the open command on the object we created earlier, set the option to GET and point it to the external data file we specified when calling the function.
Once that is done, we can output a message to the <div> we assigned to the variable obj by using .innerHTML=

We'll just put this function in place of the "hello world" message that we put in the last tutorial..

The whole code looks like this...

HTML:
  1.   <head>
  2.     <title>FiddyP AJAX tutorial, open the object</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.  
  11.       function getData(dataSource, divID)
  12.       {
  13.         if(XMLHttpRequestObject) {
  14.           var obj = document.getElementById(divID);
  15.           XMLHttpRequestObject.open("GET", dataSource);
  16.           obj.innerHTML="Oranges Box Opened!";
  17.         }
  18.       }
  19.     </script>
  20.   </head>
  21.  
  22.     <H1>Fetching data with Ajax</H1>
  23.     <form>
  24.       <input type = "button" value = "Display Message"
  25.         onclick = "getData('oranges.txt', 'targetDiv')">
  26.     </form>
  27.     <div id="targetDiv">
  28.       <p>The Oranges box will go here.</p>
  29.     </div>
  30.   </body>
  31. </html>

You can copy the contents of the HTML shown above and save it as a HTML file, you can also create a file called oranges.txt and put it in the same directory as the HTML file. (it doesn't matter what is in the text file as we wont be doing anything with it other than to open it). Open the HTML file in your browser and try it yourself or click here to see it in action if you can't wait.

That's it for this week, we're still not doing anything major yet but, be happy! we have so far, created an object and opened it. YEY! come back for part 4 where we will prepare to download information from the file we opened. (oh, I bet you can't wait!!)

beep beep w00t!

Popularity: 6% [?]

Category : Code | ajax

Related Posts

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


    Comments

    Dawn (1 comments.) December 11, 2007

    Hi there - I came to d/l the commentluv plugin but the plugin page is ummmm…. screwed. LOL Wasnt’ sure if you were aware of it.

    Dawn’s last blog post..Christmas is?

    Andy Bailey December 11, 2007

    Dawn » thanks for letting me know Dawn, it was the paged comments plugin that was having problems with so many comments happening. I have disabled comments and had to prevent more than 25 showing so the bandwidth wont go through the roof, it’s already had over 7000 single views and that is only since I installed the post views plugin a few weeks ago… it should be all dandy now and there is a page on the wordpress codex for it so I use there as the download link now.

    witchypoo (43 comments.) December 12, 2007

    My eyes do glaze over with a new language. I remember going bonkers in school, after coding in visual basic, then switching to java. Another language will add to the insanity but I am so considering the php thing. I have a book, and I’m a bit afeared, but it can be so helpful in so many ways. Ajax? I cannot go there yet.

    witchypoo’s last blog post..Grammie?s coffin - the backstory

    Vladimir (15 comments.) December 13, 2007

    Can you recommend some sites with creative usage of AJAX? It looks very interesting but where is the time to learn all this? ;)
    Vladimir’s last blog post..Smart ways to enhance your blog?s RSS feed

    Andy Bailey December 13, 2007

    witchypoo: I love learning new languages, it’s what makes me tick :-)
    Vladimir: have a search for ajax libraries, there’ll be loads of examples on those sites.. somehow there’s always time to try a new function :-)

    Ramendra (1 comments.) December 13, 2007

    the example in this tutorial is not working, when i copied the code and saved it as ajax2.html and also created the oranges.txt in same directory. But when i opened, it gave an error in following line
    “XMLHttpRequestObject.open(”GET”, dataSource);”
    so will any one let me know what goes wrong.

    Thanks
    Ramendra

    Andy Bailey December 13, 2007

    I just copied and pasted the code shown above into a text file and saved it as a html file and opened it, everything seemed to work on this end..
    maybe the ” quotes have changed after you pasted the code, check to make sure they are the proper type of quotes and see if that’s it..

    ramendra December 13, 2007

    nope, its not working i tried it all ways… well can you suggest me a good book for learning ajax, as i m just novice.

    Andy Bailey December 13, 2007

    if you check the link at the bottom of the post for the demo you can see it working, copy the source of that and save it as html to see if it’s just your computer that is having a problem with it.

    I am currently working my way through AJAX Blueprint it’s a good book with lots of step by steps

    I looked at your source and it turns out to be the most common problem, a spelling mistake! variable names in javascript always seem to mix upper and lower case so be sure to check all variable names if you get a “not defined” error

    AntiBarbie (40 comments.) December 13, 2007

    You are really good with the whole tutorial thing. Once you get the entire thing up I am going to give it a go. I hate learning in bits and pieces and have to do it all in one shot. I’m actually a little embarrassed that I’ve never worked with Ajax before. I really need to expand my coding knowledge. I don’t know half as much as I’d like to.

    AntiBarbie’s last blog post..I was feeling sorry for myself…

    Andy Bailey December 13, 2007

    I was going to put the whole thing up at once but I learned it piece by piece and it was much better knowing what each step did before I did the whole thing (plus I can serialize it on the blog much easier) :-)

    I don’t know a tenth of what I’d like to know! I still haven’t got around to using classes in php yet. They still mystify me!

    Dave January 6, 2008

    The above code should read….

    <code removed due to conflict with page html>

    Andy Bailey January 6, 2008

    thanks, I am aware that it needs XMLHttpRequestObject.send(null); in the code to be complete but this is part of a continuing tutorial series where each part continues on from the last so each code snippet is not meant to be used on it’s own.
    Part 5 introduces XMLHttpRequestObject.send(null); into the code.
    and this part of the code does do what it’s supposed to and that’s just to demonstrate the steps up to opening an object.

    but thanks anyway!

    Dave January 6, 2008

    Yeah no prob Andy,,, was just replying to the guy who was having trouble making it work.

    Andy Bailey January 6, 2008

    thanks, it turned out that he had spelled one of the variable names wrongly!

    Andi Eko (1 comments.) January 8, 2008

    I still don’t get it about reading txt files by using datasource. How to parsing the datasources ? Maybe I need to read more from articles .. Thxs

    Andi Eko’s last blog post..Membuat link Cell Ranges dengan cepat

    Andy Bailey January 8, 2008

    Andi: this particular bit of code only displays what is inside the text file, if you want to parse the text file and do something with the contents then you will need to call a php script that then opens the text file, parses it, does something with the data and then echo out the result.

    Leave a comment

    19 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