Beginning AJAX using the YUI Library

This is a real into level tutorial. The target audience for this entry is people who find http://developer.yahoo.com/ a bit overwhelming. If you think it’s a cinch, this will be below your level. If you want a more detailed intro than what they have on the YUI site, then continue on.


Preparation Step:
Create a text file and save it at include.html. Include some basic html in this page.

<h1>Hello World</h1>
<p>This is my first AJAX call</p>

Now, let’s set up our first AJAX web page using the YUI library. Our page will simply include the content from include.html when a button is pressed. Let’s begin….

Step 1: Start a new XHTML document with a typical template:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>My First Ajax using the YUI Library</title>
</head>
<body>
</body>
</html>

Step 2: Adding script calls to include the YUI library components we will be using.

<script src="http://yui.yahooapis.com/2.2.2/build/yahoo/yahoo-min.js" 
   type="text/javascript"></script>
<script src="http://yui.yahooapis.com/2.2.2/build/connection/connection-min.js" 
   type="text/javascript"></script> 

Notes:

  • As we discussed in the earlier blog entry "Including Javascript in XHTML , you must include the type attribute, but do not include the language attribute.
  • While in production you should put these calls at the end of your body, for this exercise, go ahead and put these in your header (after the meta character type and the title).
  • These scripts include minimized versions of the YUI library. Minimized means that the code base was minimized, with extra characters, comments and spacing removed. This makes the file smaller so the bandwidth is less, but it makes it human un-readable. The full version can be downloaded from The YUI distribution library.

Step 3: Create a <div> with an id in the body of your page and a link that will call the AJAX function. The div will be filled with the response from our AJAX call. Include an onclick event handler in the link. There will be another tutorial soon on using the YUI event utility to dynamically include event handers (separating presentation from the content). Make sure that the link’s href leads to a real page. Web standards and accessibility guidelines state that all links should really be links!

<div id="mydiv>
</div>  
<p><a href="/include.html" onclick="callAJAX(); return false;">
    My first AJAX</a></p>

Step 4: Add a script tag to your page. This is where we are going to put all the javascript AJAX functionality

<script type="text/javascript">
  //<![CDATA[  		

  //]]> 
</script>

This is what we have thus far:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>My First Ajax using the YUI Library</title>
<script src="http://yui.yahooapis.com/2.2.2/build/yahoo/yahoo-min.js" type="text/javascript"></script>
<script src="http://yui.yahooapis.com/2.2.2/build/connection/connection-min.js" type="text/javascript"></script>
</head>
<body>
<div id="mydiv">
</div>
<p><a href="/include.html" onclick="">My first AJAX</a></p>

<script type="text/javascript">
//<![CDATA[

//]]>
</script>
</body>
</html>

Save your file as myfirstajax.html. The script we write will be added between the CDATA open and closing tag. For more on why we use CDATA, refer to the entry on how to Include Javascript in XHTML. If you prefer, you can make a single external javascript call and add everything to that external file. If you open it up in a browser all you should see in one link that reads "My first Ajax". The page should validate.

Step 5: Add the YUI Connection Manager utility line of code that initiates an asynchronous transaction. Put this line of code in your javascript:

var transaction = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback, null);

Explanation:

  • The YAHOO.util.Connect.asyncRequest method starts an XMLHttpRequest. It returns a transaction object that has properties that you can use, including status, responseText, responseXML and tId.
  • The first argument is the HTTP method. We will cover POST and GET. The YUI connection manager also supports other HTTP methods, but POST and GET are the most common. Think of the XMLHttpRequest as a form submission: choose the HTTP method the same way you would choose a form submission method.
  • The second argument is the URL to which you are submitting the XMLHttpRequest. Think of it as a form action. It is the response page we are requesting.
  • callback, the third argument, is a series of functions that we will define to handle the server response.
  • The fourth argument is only used if the first method is 'POST'. Since we are using 'GET', we can set it to null or omit it. If we were using POST, the fourth argument would accomodate our POST message.

Step 6: Define the second parameter: the URL.  The second parameter needs to be set to the URL of the file we want to interact with asynchronously.  In this case we are simply going to include our static page — include.html — created in the preperation step before step 1.

var sUrl = "include.html";

Step 7: Define the third argument: the callback. We’ll add alerts so you can test at this point to see if it works. We’ll replace the success function after we test to see if everything is working thus far. success is the handler code that executes when the XMLHttpRequest is successful. failure is the handler code that executes if the XMLHttpRequest is unsuccessful.

  var callback = { 
     success: function(o) {
        alert("AJAX Works"); //SUCCESS 
        }, 
     failure: function(o) {
        alert("AJAX doesn't work"); //FAILURE
     }
  } 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>My First Ajax using the YUI Library</title>
<script src="http://yui.yahooapis.com/2.2.2/build/yahoo/yahoo-min.js" type="text/javascript"></script>
<script src="http://yui.yahooapis.com/2.2.2/build/event/event-min.js" type="text/javascript"></script>
<script src="http://yui.yahooapis.com/2.2.2/build/connection/connection-min.js" type="text/javascript"></script>
</head>
<body>
<div id="mydiv">
</div>
<p><a href="/include.html" onclick="callAJAX(); return false;">My first AJAX</a></p>

<script type="text/javascript">
//<![CDATA[

var sUrl = "include.html";
var callback = {
success: function(o) {
alert("AJAX Works"); //SUCCESS
},
failure: function(o) {
alert("AJAX doesn’t work"); //FAILURE
}
}

var transaction = YAHOO.util.Connect.asyncRequest(‘GET’, sUrl, callback, null);

//]]>
</script>
</body>
</html>

Step 8: Save everything and upload both include.html and myfirstajax.html into the same directory on your server. Open http://www.yourserver.com/yourfolder/myfirstajax.html in a browser. If you have an error in your code or didn’t load include.html and myfirstajax.html into the same directory, you’ll get the ""AJAX doesn’t work" alert. If you copy the code in the box above, and uploaded both files correctly into the same directory on your server, you will get the "AJAX Works" alert. If all is good, continue.

Step 9: Our goal for this project is to make the content from your external file
include.html appear on your page. We’ve created a connection to our file. We created a place holder div in step 3 with <div id="mydiv>
</div>
. We are going to target this div, and insert the content from include.html into the div with innerHTML.

Replace

 success: function(o) {
	alert("AJAX Works"); //SUCCESS 
    },

with

 success: function(o) {
    	document.getElementById('mydiv').innerHTML =  o.responseText;
    },

The left hand side of the above statement uses the DOM to target the content of mydiv.  The function takes the responseText value of the transaction and replaces mydiv’s innerHTML with the content retrieved by the XMLHttpRequest. Save, upload and test again!

Step 10: The power of AJAX is being able to make a XMLHttpRequest and altering the content of the page once the page is already loaded. Let’s change our code so that instead of loading include.html while we load the page, we load it dynamically when we click on our link. We included the onclick event handler in the link in step 3.  In a future tutorial we will use the YUI event library to dynamically attach an event handler to our link, thereby seperating content from presentation.

Encapsulate the javascript into a function.  Our onclick event handler in step 3 reads <a href="/include.html" onclick="callAJAX(); return false;">, so we will call our function callAJAX().

function callAJAX(){
	var sUrl = "include.html";
	var callback = { 
		success: function(o) {
			document.getElementById('mydiv').innerHTML =  o.responseText;
			}, 
		failure: function(o) {
			alert("AJAX doesn't work"); //FAILURE
			}
		} 

	var transaction = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback, null);
} 




The return is included in the eventhandler, so we don’t need to add it to the function. You could also have written the event handler as:

<a href="/include.html" onclick="return callAJAX();">

and added the return to the callAJAX function right before the function close:

 var transaction = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback, null); 
	return false; 
	}

Test the AJAX file


This entry was posted in AJAX, JavaScript, Web Development. Bookmark the permalink.

16 Responses to Beginning AJAX using the YUI Library

  1. Robert says:

    Thanks, the explanations of how the YUI library functions works, was very useful!!

  2. karthik says:

    how to fill the gap using css?

  3. charlie says:

    The response is not as expected. If you changed the content of include.html, then reshresh the myfirstajax.html. The change won’t updated in the myfirstajax.html page!!

  4. Pranay says:

    Amazing ! Fool Proof intro to AJAX using YUI lib.
    A definite first timers read.

  5. Estelle says:

    @Karthik: I’m sorry but I don’t understand your question.

    @Charlie: I am not getting the same results as you. My page refreshes when i change the text. I am wondering if your browser is caching the page. What browser are you using?

  6. thomas says:

    works fine! but what if the target urls´ header contains
    javascripts to be loaded on load. then it some functionality on the inline loaded html does not work.

  7. lechuman says:

    Good explanations, thks a lot, very usefull.

  8. Sergei says:

    Quick question.

    Is there a way to have all clicked links and submitted forms on the AJAX loaded page return the results to that “mydiv” container?

  9. Ed says:

    How would you do the same as you have instructed above in the tutorial, but retrieve JSON from a database instead of “include.html” (and convert the JSON to a Javascript object)?

  10. tom says:

    Hi, lovely stuff, but how can I correctly assign this function to more than one button calling more than one include file? that would need som var ID into each onclick event no? please help.

    respect Tom

  11. Manasi says:

    Excellent intro for beginners to AJAX! Thanks a ton!

  12. VINOD says:

    but here when you refresh the page, you loose the contents of the page and going back to the orignal contents, how to keep the result in the page when you refresh ?

  13. Yasar says:

    Hi I am looking to implement the yahoo widget treeview.

    I have little idea where to start, and have read the API docs, but they seem to explain how each widget works rather than how they are used.

    A guide similar to the above for this treeview would be great.

    I currently have a tree diagram setup in page /test.aspx, but the problem is that I don’t want the links to webpages to viewable in ‘view source’.

    Hope you can help.

  14. Onur says:

    Excellent intro for beginners to AJAX! Thanks a ton!

  15. Atul says:

    Hi,
    i did put both the files int he same directory. But still its not working.

  16. Hans says:

    Well done ! This is a great introduction to YUI !
    Thank you Estelle !

Leave a Reply

Your email address will not be published. Required fields are marked *