Tuesday, December 23, 2008

Ajax is so simple using JQuery

I recently started using JQuery and found that it has made JavaScript so simple and easy. For those of you who use Ajax simply , first you have to check if XmlHttpRequest object is available. If not then u try some ActiveX object untill to attain cross browser compatibility. This is all a very tiresome and repitative work.

JQuery on the other hand handles all the issue and make our script cross browser compatible. It supports IE 6.0+, Firfox 2.0+,Safari 2.0+ and Opera 9.0+.

Let us take an example. I want to get a list of US cities from a php page.

php code: cities.php
<?php

$cities = array(
'Annapolis MD',
'Atlanta GA',
'Augusta ME',
'Austin TX',
'Baton Rouge LA',
'Bismarck ND',
'Boise ID',
'Boston MA',
'Carson City NV',
'Charleston WV',
'Cheyenne WY',
'Columbia SC',
'Columbus OH',
'Concord NH',
'Denver CO',
'Des Moines IA',
'Dover DE',
'Frankfort KY',
'Harrisburg PA',
'Hartford CT',
'Helena MT',
'Honolulu HI',
'Indianapolis IN',
'Jackson MS',
'Jefferson City MO',
'Juneau AK',
'Lansing MI',
'Lincoln NE',
'Little Rock AR',
'Madison WI',
'Montgomery AL',
'Montpelier VT',
'Nashville TN',
'Oklahoma City OK',
'Olympia WA',
'Phoenix AZ',
'Pierre SD',
'Providence RI');

$count = isset($_POST['limit'])?$_POST['limit']:count($cities);
//$count = count($cities);
for ( $i = 0 ; $i < $count; $i++ ){
echo $cities[$i];
if ( $count-1 > $i )
echo "|";
}

//outputs city1 | city2 | city3 ...... | city n
>

Now we come to out html page in which we'll call the above page through Ajax.

first we'll have to include the latest version of JQuery . You can download it from its homepage jquery.com

html page: main.html

First we include jquery library which we have just downloaded.

<script type="text/javascript" src="jquery.js"></script>

We create an empty div in html part with id city in which we'll dump our data coming through Ajax.

<div id="a1"></div>

Get Ready for the action :P we are going to make our first Ajax request using Jquery's $.get method.

Get Method
prototype : $.get(url,data,callback)
url is cities.php in our case, we won't send any data now , callback function is called when data is received successfully .

$.get("cities.php",function(data){
//We get an array of citites
var d = data.split("|");
for ( i = 0 ; i < d.length ; i++ )
{
$("<li>" + d[i] + "</li>").appendTo("#a1");
}
});

And voila ! Our data is received and set into div with id a1, in a list.

So simple, Now we do it with a post request and send a variable limit so that only limit number of cities should be recieved and you'll see how beautifully it is done through jQuery.

Post Method:
prototype : $.post(url,data,callback,type)
url is cities.php in our case, we'll send limit = 3 which will be a key value paired data , callback function is called when data is received successfull and type could be either json or xml but we won't specify here as its optional.

$.post("cities.php",{limit:3},function(data){
//We get an array of citites
var d = data.split("|");
for ( i = 0 ; i < d.length ; i++ )
{
$("<li>" + d[i] + "</li>").appendTo("#a1");
}
});

This time you'll see that we get only 3 cities. Thats because in php code we specified that if $_POST['limit'] is set than use it rather than the length of actual array.

So you see how simple was it to send a post data without any headache to a page and get response.

One additional method that I would like to discuss is load(url,data,callback)

Load Method:

In most of the cases we just want to dump whole response into one div or a span of a particular id. This helpfull method does all that for you.

$("#a1").load("cities.php",{limit:3},function(data){
alert("Only top 3 cities have been received and loaded into id a1");
});

And that was all the Ajax using JQuery. I hope you have found it easy to go through JQuery's way of Ajax as I have.

1 comment:

  1. awesome sharing brother keep writing good stuff, JQuery is an awesome framework obviously and should be supported! Keep writing.

    ReplyDelete