Archive for July, 2008

A Simple AJAX Example: Searching Australian Postcodes (with JQuery)

Lately I have been writing dashlets for the SugarCRM open source CRM solution. It uses JQuery as part of its JavaScript libraries.

I have really been enjoying writing JavaScript with JQuery; it has saved me time writing concise code which also helps me debug and maintain it. So I thought it would be a good idea to rewrite my Ajax example with JQuery to compare its usefulness.

In my previous code I had to first create the XMLHttpRequest object:

var xmlHttpReq;   

// Determining which browser we are dealing with 
if (window.XMLHttpRequest)
{
   xmlHttpReq = new XMLHttpRequest();
   xmlHttpReq.overrideMimeType('text/plain');
}
else if (window.ActiveXObject)
{
   // this is required if the browser is IE
   xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}

Then I had to prepare the query string and post to the script that would get the me the details:

// generate the query string to post to the script
var queryStr = 'PostCode=' + escape(postcode);

var strURL = 'postcode_lookup.php';

xmlHttpReq.open('GET', strURL, true);
xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttpReq.onreadystatechange = displayPostcode;

// post to script
xmlHttpReq.send(queryStr);

That is too much work! With JQuery things are much easier:

$.get("postcode_lookup.php",
      { PostCode: jQuery('input[@name=PostCode]')[0].value },
      function(data)
      {
         /* Logic to parse data and determine output goes here */

         // Writing output into div
         $("#outputDiv").html(output);
      }
);

That’s it! All it takes is one function to make the Ajax call and then parse the data from the script.

The jQuery.get( url, [data], [callback], [type] ) function takes four parameters. But we are only using three as the last one is optional:
1. The script: postcode_lookup.php.
2. The parameters for the script contained in an array. In this case the value of the text field:
{ PostCode: jQuery(‘input[@name=PostCode]‘)[0].value }
3. The callback function to handle the data returned from the script.

I am quite happy for the amount of work that it has saved me. However I cannot emphasize enough how important it is to understand how the XMLHttpRequest works.

You can find the working example here.


Hello

My name is Marcel Tjandraatmadja, and I live in Melbourne, Australia. I have a special interest in PHP and web applications.
I also enjoy problem solving with C#, C, and C++.

My interests are also Aikido, roller blading, and music from my favorite bands.

Curriculum Vitae

Download my CV here.

Contact

Drop me a message at marcel.tjandra@gmail.com.

my del.icio.us

Posts

html hit counter