18 Comments »

In AJAX Fast and Easy – part one, we defined AJAX and decided it wasn’t really that complicated.
In AJAX Fast and Easy – part two,
we created an index.html file, a backendHTML.html file and we downloaded the
Prototype Javascript framework. We put them all together and made some
ajax magic happen. However, in part 2 we left out all the junk about XML, and all we really did was display
the ajax results as an alert. Not too useful, but it proved the point and it was pretty fun.

Today we are going to kick some ajax ass. We are going to get it to do all kinds of useful junk for us. First
we will make an ajax call to our backend page and stuff that response into our index page. Then we will
make an actual XML file, call it with ajax, parse the XML and render the data on our index page. By the time we
are done, you will have some pretty functional code that you will be able to use on your own projects.

Ready to get going? Ok, make sure you got all your files from part one and two in C:\ajaxHowTo\. If you lost them,
or you didn’t do part one or two, or you’re just lazy, you can
download a zip file
with all of the source code already written for you.

Just like we did in part two, we are going to take this step by step.

  • Open index.html for editing. We are going to start by writing a new function for another ajax call. Add the code from the codebox below inside the script section of index.html, just below our getSampleHTML function.
  • function getHTML() {
    	new Ajax.Request('backendHTML.html',   {     
    		method:'get',     
    		onSuccess: getHTMLSuccess,     
    		onFailure: getHTMLFailure
    	}); 
    }
    

    You’ll notice that the only difference between this function and our first function, getSampleHTML, are the onSuccess
    and onFailure pieces. What we are doing here is telling the ajax call to call two new functions,
    that we haven’t written yet, on a success or failure.

  • Now create two new functions called getHTMLSuccess and getHTMLFailure as shown in the code below.
  • function getHTMLSuccess(originalRequest) {
    	var response = originalRequest.responseText;
    	$('htmlResult').innerHTML = response;
    }
    function getHTMLFailure() {
    	alert('woops, what happened?');
    }
    

    Lets take a minute to figure out what it is we are trying to do here.

    We wrote the new ajax call and named it getHTML, nothing new, we only changed the onSuccess and onFailure calls.
    Then we created the getHTMLSuccess function. What this function does is, it accepts the ajax response as originalRequest as you can see in getHTMLSuccess(originalRequest). We create a variable named response and set
    it equal to the response text. The response text will be the html that gets sent back, just like in our alert from
    part two. The difference here is instead of displaying the response in a javascript alert, we are assigning it
    to a variable and stuffing the html response into our ‘htmlResult’ div further below in the body of our html.
    Are you asking “where the hell did we do that?” No problem, I kind of snuck it in there. The prototype
    framework has some cool special shortcuts for doing everyday javascript junk. In this case, we have the $ sign.
    The $ sign with prototype is used as a shortcut for “document.getElementById(‘htmlResult’)”. If it still doesn’t
    make sense, just take my word for it. The $(‘htmlResult’).innerHTML = response; line will insert the ajax
    response into our htmlResult div and the content on the page will be magically updated.

    The second function we wrote is getHTMLFailure. As you can tell, its only job is to show an alert if a failure occurs.
    Normally, under these circumstances, the only time you can get a failure is if the backendHTML.html file can’t be found.

  • So, what’s next? Well, nothing really, we just wrote some kick ass ajax code that will go get the contents of any
    file we decide to put in the Ajax.Request(‘backednHTML.html’) section of our function. If we open up index.html and
    click on ‘call getHTML()’ we should see the text on the page change and the contents of backendHTML.html should
    magically appear at the bottom of the page.
  • That’s ajax man! That’s really all there is to it. Just like in part two, we use prototype to
    make an ajax call to our backend page, but instead of showing the response in an alert, we display it on the page.
    Much more useful if you ask me.

    Now it’s time for us to put it in high gear and see what this ajax stuff is really all about and how it got its name.

  • Open your favorite text editor and make a new document. Enter the code displayed in the code block below, and save the
    file as backendXML.xml in your ajaxHowTo folder.
  • <?xml version="1.0" encoding="UTF-8"?>
    <books>     
    	<book>     
    		<title>The Shining</title>     
    		<author>Stephen King</author>     
    		<ISBN>0743437497</ISBN>     
    	</book>     
    	<book>     
    		<title>Fahrenheit 451</title>     
    		<author>Ray Bradbury</author>     
    		<ISBN>9506440298</ISBN>     
    	</book>     
    </books>
    
  • We will create a new ajax function to call this new file. Open up index.html and create a new function just like the one
    in the code box below. This function is the same as the getHTML function we just wrote, we only change the URL we call,
    and the onSuccess function name.
  • function getXML() {
    	new Ajax.Request('backendXML.xml',   {     
    		method:'get',     
    		onSuccess: getXMLSuccess,     
    		onFailure: getHTMLFailure
    	}); 
    }
    
  • Next we write our most complicated function of the entire project. Add the function in the code box below to index.html,
    and we will walk through what it’s doing line by line. Don’t worry, it will make sense, but it is some pretty complicated
    stuff. Javascript is like ice skating, when it’s done well, it looks easy. And, I think it should be.
  • function getXMLSuccess(originalRequest) {
    	var response = originalRequest.responseXML;
    	var numberOfBooks = response.getElementsByTagName('book').length;
    	var titles = response.getElementsByTagName('title');
    	var authors = response.getElementsByTagName('author');
    	var isbns = response.getElementsByTagName('ISBN');
    	var resultText = "";
    	resultText = "Total number of books = " + numberOfBooks;
    	for( i=0; i<numberOfBooks; i++ ) {
    		currentTitle = titles[i].firstChild.nodeValue;
    		currentAuthor = authors[i].firstChild.nodeValue;
    		currentIsbn = isbns[i].firstChild.nodeValue;
    		resultText = resultText + "<p>";
    		resultText = resultText + "<br/> Book " + (i+1);
    		resultText = resultText + "<br/> Title = " + currentTitle;
    		resultText = resultText + "<br/> Author = " + currentAuthor;
    		resultText = resultText + "<br/> ISBN = " + currentIsbn;
    		resultText = resultText + "</p>";
    	}
    	$('xmlResult').innerHTML = resultText;
    }
    

    Just like the earlier function we wrote, getHTMLSuccess, this new function accepts originalRequest as the ajax response.
    We assign the response to a variable named response, but this time we use originalRequest.responseXML instead of
    responseText. That part is important and you must use responseXML if we are going to parse the XML file to extract the
    data we want from it.

    The reason we would do this is because, unlike making an ajax call to an HTML file and displaying the entire file,
    we want to call an XML file and only extract the specific data that we want from it. Remember in part one, we said that
    the XML nodes only define what the data means? Well, the tag doesn’t mean anything to an HTML file, so why would
    we want to render that on our HTML file? We wouldn’t, but we would probably want to render the book name and that’s
    what we are about to do.

    First we need to find out how many books we have, so take a look at the numberOfBooks variable. This variable counts the
    book nodes. In this case there are two. The next variable is titles, this variable gets all the nodes named title from
    the XML. The same goes for authors, and isbns.

    We define an empty string called resultText that will be a place holder for some HTML we will build in a minute. We then
    start adding text to the new resultText string to display the total number of books found on the XML file.

    Next we create a loop to repeat the same procedures for each book, in this case we will loop twice. Our loop creates
    three variables and assigns the node values to them. I’ll give one example of how it works and the rest should be self-explanatory. currentTitle = titles[i].firstChild.nodeValue means that on the first round of the loop we are looking
    for titles[0].firstChild.nodeValue, which means… Give me the nodeValue, in this case ‘The Shining’ of the first item
    in the XML file named title (<title>The Shining</title>).

    The rest of the script just does the same thing over and over again for as many books as we have in the XML file. We get
    the values from the XML, we assign them to variables, we attach the values to the resultText variable, we add some
    normal HTML junk around them to make them look pretty, then we do the prototype magic again.

    We use the $ sign to update the div xmlResult with the text we just created in our resultText variable. Again, this is
    nothing new, its simply document.getElementById(‘xmlResult’).innerHTML = “the junk we just looped through”.

  • Open your index.html file in the browser and click on ‘call getXML()’. You should see the ajax magic happen before your
    eyes and text should magically appear on the page. Again, if you don’t feel like doing any of this, just view the
    sample page that I made and click the link.
  • That example took a little longer to explain, but that is pretty much everything you need to know about ajax.


    Page A makes an AJAX call to page B, and page A displays the content of page B.

    If you want to call an HTML page, fine. If you want to call an XML file to extract data from, fine. Either way, you
    have a page that makes a call to a backend page. Normally you will have some sort of server side technology on the
    backend page like PHP or java that runs database queries and gets dynamic content, but that has nothing to do with
    ajax itself.

    I am a huge fan of the Prototype Javascript framework, and
    there are ton of other shortcuts like the $ sign built into it. There are also other ways to make ajax calls with prototype
    that actually make the job we just worked even easier, but for the sake of the explanation, we didn’t use them. I
    will try to put together another post that goes over some of the most useful things you can do with prototype in the future.

    Here is a cheat sheet for prototype
    that you will probably find useful.

    Well, that’s it. Now you know ajax. It’s no big secret, it’s not complicated, and it’s pretty fun.

    What would you like the hear about next?

     



    Tags: , , , , , , , , , ,

    Trackback URL | Comments RSS

    18 Responses to “Ajax Fast and Easy – part three”
     

    […] Ajax Fast and Easy – part three […]

     

    I just found a new cheat sheet for prototype 1.6

    webandnow wrote on March 2nd, 2008 at 11:40 am

     

    Great stuff! Thanks!

    Bob wrote on March 7th, 2008 at 12:24 pm

     

    For some reason, recreating the files doesn’t work on my computer with Windows XP and MS iExplore 7.0.
    Also the unzipped file doesn’t work with iExplore 7.0.
    However it does work with FireFox 2.0

    Your sample page link does work with iExplore 7.0.

    Can you explain that?

    ThierryH wrote on March 9th, 2008 at 3:42 pm

     

    Client based JavaScript and XML do work in IE7.
    What is the problem with ajax running on a client in IE7?

    ThierryH wrote on March 9th, 2008 at 4:05 pm

     

    I mention in part 2 that running the code from a folder will work with firefox, but it will not work in IE unless you run the code on a webserver. It has to do with the way IE understands the path for the ajax call. If you would like to run a webserver, you may want to look into apache.

    webandnow wrote on March 9th, 2008 at 7:58 pm

     

    I was curious what created that problem and if there was a way to solve it. I’m used to dig until I understand why it works the way it does.

    In the meantime I tried the example after copying it to my URL. It works fine.

    Thank you very much for this great article and the way you approach it. I feel like ready to get to this next step.

    ThierryH wrote on March 10th, 2008 at 12:44 pm

     

    this blog post on Software in Seattles blog has a pretty good explanation of the problem of why IE cannot make ajax requests to the local filesystem. I am not positive, but I would assume there could be one of 2 reasons for this behavior in IE.
    1. IE is just kind of broken
    2. IE may prevent ajax calls to the local file system for security reasons, imagine if i hardcoded c:/windows/ as an ajax request, then theoretically, some malicious site could read data from your local filesystem.
    Im not necessarily a security expert, so i cant actually explain the problem definitively, but those would be my guesses.

    webandnow wrote on March 10th, 2008 at 1:19 pm

     

    Thank you for the great approach to learning Ajax.

    Next step…practical uses.

    Can the backend call be used in conjunction with css to replace existing information in an html page… Clearing when you do not want to view the new information any more?

    Jay Benoit wrote on March 10th, 2008 at 4:46 pm

     

    Im glad you had a chance to read it, i hope it helps.
    I would be more than happy to write a series on practical uses of ajax.
    As far as your question, the answer is yes. after you call the backend and get your response, you can manipulate it with css, dhtml, javascript, whatever you want, there are some situations that need special attention, and some situations where you may need to programmaticly notify the DOM of an update, but for the most part you can update, change and remove information from the page all you want.
    Actually, you make a great point, i should write a follow up article that describes when you would use ajax, and its role in web development.
    That is sort of what i was trying to get at, i guess, in the article. the point was to show that ajax itself is very simple, and throwing the word ajax around is almost silly because it is so simple, what people are normally talking about when talking about ajax is more often a combination of 1% ajax, and the rest javascript, css, dhtml, xhtml, and popular libraries that make doing all this work easier such as
    http://wiki.script.aculo.us/scriptaculous/show/CombinationEffectsDemo
    or
    http://www.javascriptmvc.com/

    if you have a particular scenario that you would like described, please let me know and i’ll try to explain it as best i can.

    webandnow wrote on March 10th, 2008 at 11:07 pm

     

    Thank you,Its good,I learned Ajax from this.

    deepthi wrote on March 11th, 2008 at 12:16 am

     

    Thank you very much!
    This article is useful to me !

    wwj wrote on March 12th, 2008 at 7:54 am

     

    Can you sort your rows in an AJAX request?
    If so, can you give an example of sorting your book list alphabetically by author, by title?

    (awesome tutorial!)

    opally wrote on March 14th, 2008 at 1:42 pm

     

    ajax really only makes the request and gives the response. It would be up to you to sort the result, and the best way to sort would be to do it in a database query. so you would want to generate your xml with a query like:

    select * from books
    order by title

    then output the results of that query as xml, ajax will give it back to you however you decide to write the xml.

    webandnow wrote on March 18th, 2008 at 11:36 am

     

    Thanks a lot for the tutorial it was easy, simple and clear for me. I’d like to see some follow ups as mentioned above. Just as a comment, in the snippets of code you forgot to include the code of the clearNode function, since I copied and pasted all the code from your web page and when testing mine it showed me that that funcion was missing.

    Keep on going and hope you post some more helful hints and the ones you already did.

    Marco wrote on March 18th, 2008 at 3:01 pm

     

    You are right, I didn’t actually go over the clearNode function in this article, however it is in the sample code that you can download to review the source. here is clearNode, add this to your script tag in the head…
    function clearNode(node) {
    $(node).innerHTML = “”;
    }
    it just clears out the text we added with the ajax call.

    webandnow wrote on March 18th, 2008 at 4:54 pm

     

    Thanks ,

    Can ajax change contain of the third .
    example : i have index.html ,prototype-1.6.0.2.js ,backendXML.xml .
    And I want to include third file who will depend on index.html and backendXML.xml .

    Anonymous wrote on March 21st, 2008 at 12:47 am

     

    Im not sure i completely understand the question, but you can use ajax to call any number of files.
    sorry, im sure that is not much help. perhaps you could explain you question a little more for me.

    webandnow wrote on March 21st, 2008 at 9:23 am


     




  • songs of agent vinod
  • download enrique iglesias escape video
  • jboss as community download page
  • mp3 of jannat 2 songs
  • peter john young folks mp3
  • kala doria song free
  • shin chan mp3 download
  • sorry board game
  • jaws theme song download mp3 skull
  • phir wohi raat hai song download
  • minecraft map er mod
  • fazer download do ares em portugues gratis
  • end of all time
  • anjunabeats volume 9 mixed by above & beyond free
  • soy incondicional prince royce download
  • trAnh duyat opera
  • a histA?ria de ester completo
  • el malo remix mp3
  • bound by darkness alexis morgan free download
  • les miserables 25th anniversary cd free
  • let me down mp3
  • seikon no qwaser mp4
  • rashid bhikha nasheed download
  • orange range hana free download
  • sims 2 custom content no s folder
  • portal 2 pc ita iso
  • jagjit singh mp3 download songs
  • vga driver windows xp download free
  • lagu jawapan cintaku sedalam lautan atlantik
  • mp3 software free youtube
  • windows 7 s folder takes long time
  • 6 8 12 download brian mcknight
  • prezioso feat marvin song 2 download
  • download theme os 7 for blackberry 9780
  • tds rates for ay 12 13
  • iqbal bano songs mp3 free download
  • ultimate dvd burner
  • grupo bom gosto 2012 cd
  • online movies download hindi new
  • video songs of yes boss
  • carter 4 deluxe download zip
  • http er free
  • cnet downloads for windows 7
  • interviul vietii mele free
  • world championship rugby ps2
  • costi ionita si sahara champagne
  • tom jerry movie free download cartoon
  • cs 1.6 for kids download free
  • download do nero vision em portugues
  • how to a video from youtube for free
  • garth brooks against the grain mp3 download
  • windows 8 consumer preview folder
  • battlefield vietnam demo free
  • mysql client for linux
  • stela enache & florin bogardo ani de liceu fisierul meu
  • crossfire multi hack v1.6.dll
  • serious sam ii download full game
  • bb storm facebook
  • katekyo hitman reborn episode downloads
  • sete de noi ellie white
  • tom zA blog download
  • fifa 13 polski komentarz chomikuj
  • download de che mu xanh aoe 1
  • marley e eu download legendado avi
  • sve mape za cs 1.6 download free
  • festival 2012 black sabbath video
  • dolby control center.msi
  • download sleep machine app
  • slightly stoopid closer to the sun album
  • oracle golden gate software free
  • the darkest kiss free download
  • iphone 4 ipsw 5.1.1
  • 4minute hot issue song
  • ios 5 downloaden op ipod touch
  • gustavo lima balada lyrics download free
  • silverlight 4 tools for vs 2010 and wcf ria services download
  • star wars 3 movie
  • kanon standard edition english download
  • some nights free mp3 download fun
  • uae yellow pages 2010 download
  • directshow decoder 8192 download free
  • song bole chudiyan with video
  • gantung melly goeslow free mp3
  • claw game free full version for mac
  • racionais 1000 trutas mil tretas download dvd
  • down on me hulk
  • amazing grace sheet music download free
  • la roux bulletproof rar download