Skip to Main Content

Monday, April 17, 2006

Quick AJAX Overview

For those precious few who have held out on learning about AJAX, here is a quick overview of how to implement it.

AJAX Example


One of the first things you will need to do is to reference a function on an HTML element's event. In our example, we will use the <body> tag's onload event:

  1. <body onload="getData();">

Next, we create the getData() function to establish the AJAX connection and retrieve the data from the server (in this case, its an XML document).


  1. var ajax;
  2.  
  3. function getData()
  4. {
  5. //Checks if it's a modern browser
  6. if(document.getElementById)
  7. {
  8. //Creates the AJAX Object bases on browser type
  9. if(window.ActiveXControl)
  10. {
  11. ajax = new ActiveXOject("Microsoft.XMLHTTP");
  12. }
  13. else
  14. {
  15. ajax = new XMLHttpRequest();
  16. }
  17.  
  18. //If the ajax object was created successfully
  19. if(ajax)
  20. {
  21. //Process the response (calls the processResponse function)
  22. ajax.onreadystatechange = processResponse;
  23.  
  24. //XML/RSS/Web service URL
  25. ajax.open("GET", "/services/data.xml", true);
  26.  
  27. //Parameters to send to the URL (null in this case)
  28. ajax.send(null);
  29. }
  30. }
  31. }

If you notice, I'm using a .xml file. This could also be a web service, an rss feed, or even just a web page that returns xml.

Next, we create the "processResponse" function. In the code example above, we assign the ajax.onreadystatechange a reference to a function. This function will provide a way to access the response of the xml returned.


  1. function processResponse()
  2. {
  3. if(ajax.readyState == 4 && ajax.status == 200)
  4. {
  5. //Assign the XML returned to a local variable
  6. var xml = ajax.responseXML;
  7. alert(xml);
  8. }
  9. }


While the above example doesn't do anything fancy, it demonstrates how easy it is to create a quick asynchronous connection to get some data without refreshing the page.

I will be creating an XMLHttpRequest tutorial in the next post, so look forward to learning more AJAX.

Adios

0 Comments:

Post a Comment

<< Home