May 1, 2010

AJAX in 5 minutes using jQuery

One thing that really amazes me is how people can write an entire book on AJAX. It's a truly simple thing. It shouldn't even be a topic on its own, it should maybe be a subchapter in a book on Javascript or something. Anyway I'll show you how to use AJAX in 5 minutes using jQuery. You should usually use a library like jQuery (or others like Prototype or Mootools, use whichever you like the most) since using AJAX with regular old Javascript is a more tedious process with lots of repetition.

As a prerequisite to actually using AJAX in practice, you should know how to do some server-side programming using something like PHP, Ruby on Rails, etc. You should also be a bit familiar with Javascript.

All AJAX does is make a little request to the server without reloading the page. Here's some code:
$.get("profile.php", { username: "rob" },
function(response){
// put the HTML content of profile.php into a div with id = "profile_page"
$("#profile_page").html(response);
}
);
This simple example makes a request to profile.php with the parameters username = "rob", and drops the text into a div on the current page. This is effectively the same as accessing profile.php?username=rob directly, except without refreshing the page.

You can also do POST requests for mutable actions:
$.post("login.php",
{ username: "rob", password: "secret" },
function(response){
if (response == "good"){
alert("You have logged in successfully.");
}else{
alert("Invalid username/password");
}
}
);
The login action here would just output "good" if the login worked, or "bad" if the login didn't work.

There, you're now an AJAX master! Of course it would be better to learn by trying it out for yourself, but that's the basics of it all.

5 comments:

Phil said...

Excellent little tutorial. It amazes me how tutorials normally make Ajax seem amazingly complex, but with jquery, it's really simple.

Anonymous said...

AJAX is very cool when able to fit into a working scheme.

I loved your website content with learning a new way of using AJAX!
Thanks for sharing.

Norman Flecha
STRAIGHTALK
http://www.straightalk.biz

steve said...

Nice one, thanks for that.

Dave said...

Also, $.json(url, callback) will grab JSON from not only your server but any other domain with JSON objects. Yay

SS81 said...

Thanks Rob, this really is ajax in 5 minutes!