5 Ways to Make Ajax Calls with jQuery

5 Ways to Make Ajax Calls with jQuery

Tutorial Details
  • Topic: jQuery
  • Difficulty: Beginner
  • Estimated Completion Time: 20 minutes

There are at least five ways to make AJAX calls with the jQuery library. For beginners, however, the differences between each can be a bit confusing. In this tutorial, we’ll line them up and make a comparison. Additionally. we’ll review how to inspect these AJAX calls with Firebug as well.

What is AJAX

This section is for those who have no idea what AJAX is. If you don’t fall into this category, feel free to skip to the next section.

AJAX stands for asynchronous JavaScript and XML. If you see another term XHR, which is shorthand for XML HTTP request, it’s the same thing. Don’t be afraid of this jargon; AJAX is not rocket science.

  • In Gmail, switch from inbox to draft. Part of the page is changed, but the page is not refreshed. You remain on the same page. Url has not changed (except for the #draft at the end of the url, but that’s still the same webpage).
  • In Google Reader, select a feed. The content changes, but you are not redirected to another url.
  • In Google Maps, zoom in or zoom out. The map has changed, but you remain on the same page.

The key to AJAX’s concept is “asynchronous”. This means something happens to the page after it’s loaded. Traditionally, when a page is loaded, the content remains the same until the user leaves the page. With AJAX, JavaScript grabs new content from the server and makes changes to the current page. This all happena within the lifetime of the page, no refresh or redirection is needed.

Caching AJAX

Now we should know what AJAX actually is. And we know that, when Gmail refreshes some content without redirection, an AJAX call is made behind the scenes. The requested content can either be static (remains exactly the same all the time, such as a contact form or a picture) or dynamic (requests to the same url get different responses, such as Gmail’s inbox where new mails may show up any time).

For static content, we may want the response cached. But for dynamic content, which can change in a second’s time, caching AJAX becomes a bug, right? It should be noted that Internet Explorer always caches AJAX calls, while other browsers behave differently. So we’d better tell the browser explicitly whether or not AJAX should be cached. With jQuery, we can accomplish this simply by typing:

	$.ajaxSetup ({
		cache: false
	});

1. load(): Load HTML From a Remote URL and Inject it into the DOM

The most common use of AJAX is for loading HTML from a remote location and injecting it into the DOM. With jQuery’s load() function, this task is a piece of cake. Review this demo and we’ll go over some uses one by one.

Minimal Configuration

Click on the first button named “load().” A piece of HTML is injected into the page, exactly what we were talking about. Let’s see what’s going on behind the scenes.

Below is the JavaScript code for this effect:

	$.ajaxSetup ({
		cache: false
	});
	var ajax_load = "<img src='img/load.gif' alt='loading...' />";
	
//	load() functions
	var loadUrl = "ajax/load.php";
	$("#load_basic").click(function(){
		$("#result").html(ajax_load).load(loadUrl);
	});
  1. $.ajaxSetup forces the browser NOT to cache AJAX calls.
  2. After the button is clicked, it takes a little while before the new HTML is loaded. During the loading time, it’s best to show an animation to provide the user with some feedback to ensure that the page is currently loading. The “ajax_load” variable contains the HTML of the loading sign.
  3. “ajax/load.php” is the url from which the HTML is grabbed.
  4. When the button is clicked, it makes an AJAX call to the url, receives the response HTML, and injects it into the DOM. The syntax is simply $(“#DOM”).load(url). Can’t be more straightforward, hah?

Now, let’s explore more details of the request with Firebug:

  1. Open Firebug.
  2. Switch to the “Net” tab. Enable it if it’s disabled. This is where all HTTP request in the browser window are displayed.
  3. Switch to “XHR” tab below “Net”. Remember the term “XHR?” It’s the request generated from an AJAX call. All requests are displayed here.
  4. Click on the “load()” button and you should see the following.

The request is displayed, right? Click on the little plus sign to the left of the request, more information is displayed.

Click on the “Params” tab. Here’s all parameters passed through the GET method. See the long number string passed under a “_” key? This is how jQuery makes sure the request is not cached. Every request has a different “_” parameter, so browsers consider each of them to be unique.

Click on the “Response” tab. Here’s the HTML response returned from the remote url.

Load Part of the Remote File

Click on “load() #DOM” button. We notice that only the Envato link is loaded this time. This is done with the following code:

	$("#load_dom").click(function(){
		$("#result")
			.html(ajax_load)
			.load(loadUrl + " #picture");
	});

With load(url + “#DOM”), only the contents within #DOM are injected into current page.

Pass Parameters Through the GET Method

Click on the “load() GET” button and open firebug.

	$("#load_get").click(function(){
		$("#result")
			.html(ajax_load)
			.load(loadUrl, "language=php&version=5");
	});

By passing a string as the second param of load(), these parameters are passed to the remote url in the GET method. In Firebug, these params are shown as follows:

Pass Parameters Through the POST Method

Click on the “load() POST” button and open Firebug.

	$("#load_post").click(function(){
		$("#result")
			.html(ajax_load)
			.load(loadUrl, {language: "php", version: 5});
	});

If parameters are passed as an object (rather than string), they are passed to the remote url in the POST method.

Do Something on AJAX Success

Click on “load() callback” button.

	$("#load_callback").click(function(){
		$("#result")
			.html(ajax_load)
			.load(loadUrl, null, function(responseText){
				alert("Response:\n" + responseText);
			});
	});

A function can be passed to load() as a callback. This function will be executed as soon as the AJAX request is completed successfully.

2. $.getJSON(): Retrieve JSON from a Remote Location

Now we’ll review the second AJAX method in jQuery.

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It’s very convenient when exchanging data programmatically with JSON.

Let’s review an example.

Find the $.getJSON() section in the demo page, type in some words in your native language, and click detect language.

//	$.getJSON()
	var jsonUrl = "ajax/json.php";
	$("#getJSONForm").submit(function(){
		var q = $("#q").val();
		if (q.length == 0) {
			$("#q").focus();
		} else {
			$("#result").html(ajax_load);
			$.getJSON(
				jsonUrl,
				{q: q},
				function(json) {
					var result = "Language code is \"<strong>" + json.responseData.language + "\"";
					$("#result").html(result);
				}
			);
		}
		return false;
	});

Let’s jump to Line 9:

  1. $.getJSON doesn’t load information directly to the DOM. So the function is $.getJSON, NOT $(“#result”).getJSON. (There are pairs of similar looking functions in jQuery such as $.each() and each(). Check out their respective documentation for more information.)
  2. $.getJSON accepts three parameters. A url, parameters passed to the url and a callback function.
  3. $.getJSON passes parameters in GET method. POSTing is not possible with $.getJSON.
  4. $.getJSON treats response as JSON.

$.getJSON’s function name is NOT camel-cased. All four letters of “JSON” are in uppercase.

Look at the response in JSON format in Firebug. It’s returned from Google Translate API. Check out ajax/json.php in source files to see how language detection works.

3. $.getScript(): Load JavaScript from a Remote Location

We can load JavaScript files with $.getScript method. Click on “Load a Remote Script” button in the demo page; let’s review the code for this action.

//	$.getScript()
	var scriptUrl = "ajax/script.php";
	$("#getScript").click(function(){
		$("#result").html(ajax_load);
		$.getScript(scriptUrl, function(){
			$("#result").html("");
		});
	});
  1. $.getScript accepts only two parameters, a url, and a callback function.
  2. Neither the GET nor POST params can be passed to $.getScript. (Of course you can append GET params to the url.)
  3. JavaScript files don’t have to contain the “.js” extension. In this case, the remote url points to a PHP file. Let your imagination fly and you can dynamically generate JavaScript files with PHP.

See the response JavaScript in Firebug.

4. $.get(): Make GET Requests

$.get() is a more general-purpose way to make GET requests. It handles the response of many formats including xml, html, text, script, json, and jonsp. Click on the “$.get()” button in the demo page and see the code.

//	$.get()
	$("#get").click(function(){
		$("#result").html(ajax_load);
		$.get(
			loadUrl,
			{language: "php", version: 5},
			function(responseText){
				$("#result").html(responseText);
			},
			"html"
		);
	});
  1. $.get() is completely different, as compared to get(). The latter has nothing to do with AJAX at all.
  2. $.get accepts the response type as the last parameter, which makes it more powerful than the first functions we introduced today. Specify response type if it’s not html/text. Possible values are xml, html, text, script, json and jonsp.

5. $.post(): Make POST Requests

$.post() is a more general-purpose way to make POST requests. It does exactly the same job as $.get(), except for the fact that it makes a POST request instead.

//	$.post()
	$("#post").click(function(){
		$("#result").html(ajax_load);
		$.post(
			loadUrl,
			{language: "php", version: 5},
			function(responseText){
				$("#result").html(responseText);
			},
			"html"
		);
	});

The use of $.post() is the same as its brother, $.get(). Check the POST request in Firebug (shown in the following image).

Finally… $.ajax():

Up to this point, we’ve examined five commonly used jQuery AJAX functions. They bear different names but, behind the scenes, they generally do the exact same job with slightly different configurations. If you need maximum control over your requests, check out the $.ajax() function.

This is jQuery’s low-level AJAX implementation. See $.get, $.post etc. for higher-level abstractions that are often easier to understand and use, but don’t offer as much functionality (such as error callbacks). -jQuery’s official Documentation

In my opinion, the first five functions should satisfy most of our needs. But if you need to execute a function on AJAX error, $.ajax() is your only choice.

Conclusion

Today, we took an in-depth look of five ways to make AJAX calls with jQuery.

  • load(): Load a piece of html into a container DOM.
  • $.getJSON(): Load a JSON with GET method.
  • $.getScript(): Load a JavaScript.
  • $.get(): Use this if you want to make a GET call and play extensively with the response.
  • $.post(): Use this if you want to make a POST call and don’t want to load the response to some container DOM.
  • $.ajax(): Use this if you need to do something when XHR fails, or you need to specify ajax options (e.g. cache: true) on the fly.

Before we conclude, here’s a comparison table of these functions. I hope you enjoyed this lesson! Any thoughts?

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • Niklas Hansen

    I prefer $.ajax for all of my AJAX calls.

    • http://www.enatom.com Enatom

      snob

    • Rocky

      Niklas Hansen your a idiot it dosent matter how he named his ajax call he is trying to demonstrate how to make a ajax call using JQUERY your a total noob now its time for you to go and get a life!

      Stupid SNOOB!! Shame On You For Trying To De-Credit This Alsome Article

      • Stupid Rocky

        Rocky, learn to spell. Then talk.

      • http://simon.vansintjan.org Simon

        As far as I can see all he was doing was stating a preference. I don’t think it warranted that type of response (twice).

      • Rocky

        Yea i didnt realise it was a double post both in the comments section and as a reply to his post! wont happen again

      • Rocky

        Please Remove All Comments Made Using My Name.

        Every Post Made On August The 18th (WERE NOT POSTED BY ME)

        Someone who i thought i could trust is trying to tarnish my name thats the last time i let anyone on my account.

      • Rocky

        I hope this dosent effect my status on nettuts i am a very creditable person i would hate to think that my reputation is totaly tarnished because Someone went on my pc and started flamming and posting nasty comments

      • http://omarabid.com Omar Abid

        okay you made all those comments and then it’s YOUR comments that did not make a sense and not his!!!

    • David Langford

      you disgraceful, disgusting smelly old man, Park has written an orgasmic article, and your jealousy stinks to high heaven, get lost and don show your pussy eating face here ever again…

      absolutely ridiculous, WELL DONE PARK, and take no notice of Mr Hansen’s jealousy.

      • Jake

        ‘don show your pussy eating face here ever again’

        Discrimination on sexuality… really?

      • evan

        Ah man, I would hate to be a pussy eater.

        Anyway, I enjoyed the tut, thankyou. :)

      • ida

        good.Help ful to

  • http://fwebde.com/ Eric B.

    Thanks for the post! Before I knew pretty much nothing about Ajax. Now I at least have a basic knowledge of it.

  • http://www.imblog.info Muhammad Adnan

    awesome !

    • http://eyoosuf.blogspot.com Yoosuf

      Cool, AIO

  • Zack

    I think this is going to be one of my favorite posts from nettuts.

    gunna have to bookmark this page most deff!

  • Rocky

    Niklas Hansen your a idiot it dosent matter how he named his ajax call he is trying to demonstrate how to make a ajax call using JQUERY your a total noob now its time for you to go and get a life!

    • Ian

      Waita fail at replying to the actual post… and then double posting.

      • Rocky

        Epic Fail!

  • http://www.kevinbradwick.co.uk Kevin

    I’ve never tried anything other than $.post() and $.get()

  • http://www.NiklasHanseniISAWANKER.com www.Niklas Hanseni IS A WANKER.com

    Niklas Hanseni IS A WANKER, TOOL AND HE NEEDS TO BE PUTDOWN LIKE THE DIRTY DOG HE IS HES A MASTER WANKER

  • andrei009

    great article for beginners. you forget about jsonp, though

  • http://simon.vansintjan.org Simon

    Bookmarked. A great introduction to AJAX. Thanks.

  • Jerrett

    That’s not what asynchronous means :(

    • http://parkeffect.com Park
      Author

      Would love to hear your opinion. What does that mean?

  • sreenivas

    $.getScript() doesn’t work in chrome and ie6 :(

    • http://eduplessis.com eduplessis

      it’s work i use it a lot of time

  • http://yoavniran.wordpress.com Yoav

    Great article!

    I wrote an article about calling a webservice using jQuery:

    http://yoavniran.wordpress.com/2009/08/02/creating-a-webservice-proxy-with-jquery/

  • http://www.jondavis.net/ Jon Davis

    Jeez Rocky, calm down, take your meds. I agree with Niklas Hansen, I prefer $.ajax(), too. That’s a good thing, if anything he (and I) are affirming the author’s mention of that method, as opposed to, say, using non-jQuery AJAX methods for AJAX.

  • http://www.ssiddharth.com Siddharth

    Way to be snobby to the first post guy. He was merely stating he uses $.ajax for all his work. He wasn’t saying people who use the other functions are novices. There are zero reasons to jump down his throat like that.

    I use $.ajax for 99% of my work. There. Take a shot at me now.

  • http://www.antsmagazine.com Nahid

    Thanks a bunch really usefull

  • dhype

    Load() Post never reponse on “Mozilla/5.0 (Windows; U; Windows NT 5.1; es-ES; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2″
    with Firebug 1.4.2
    response” 405 Method Not Allowed “

  • px

    Thanks man !

  • Neener

    One has to appreciate the irony of the phrase “your and idiot.”

    your : /yʊər, yɔr, yoʊr; unstressed yər/ –pronoun 1. (a form of the possessive case of you used as an attributive adjective): Your jacket is in that closet. I like your idea. Compare yours.

    you’re : /yʊər; unstressed yər/
    contraction of you are: You’re certain that’s right?

    Example: If YOU’RE going to call somebody an idiot, you should correctly use YOUR contractions.

  • Deoxys

    Thanks for the best jQuery-AJAX Introduction I’ve ever read.

    But what do you want to say with that:
    $.post(): Use this if you want to make a POST call and don’t want to load the response to some container DOM.

    …. and don’t want to load the response in some container DOM??? Why did you write that?

    • http://parkeffect.com Park
      Author

      Thank you Deoxys! Sorry for the confusion.
      If I need to inject the HTML to some DOM, I tend to user load(), instead of $.get() or $.post(). Just a personal preference I assume :-)

  • http://www.sebnitu.com Sebastian

    I’ve been working on a project that uses AJAX very heavily.

    I personally prefer $.ajax just because of the amount of control you get over it.

    Here is a list of the options you can configure with $.ajax…

    http://docs.jquery.com/Ajax/jQuery.ajax

  • adil

    $.ajax accept serialize form as data

    this is good

  • http://www.digitalkreations.info kanedogg

    i don’t see it much different from reading the visual jquery documentation really …. i guess other than a little more elaboration on each?? Anyhow good work i guess……… good for newbies =o)

    • http://parkeffect.com Park
      Author

      Agree with you. They’re just about the same thing.

  • Joe

    cool

  • http://www.richardcastera.com Richard Castera

    Very informative post! Thanks!

  • jakot

    Awesome!, great article
    Thanks

  • Arnold

    yeah I agree with most of these guys said..
    I prefer also $.ajax

    thats just my opinion..alright

    but its nice to hear tuts about jquery and ajax,thanks for this
    I learn something..

  • Cuijiudai

    That is too simple ,you should use php to creat response,that is real ajax should do.

  • Merijn

    Hi Park, nice article! Love it, since i`m new to jquery. However, i do know what asynchronous means, and what Jerret was trying to tell is, your definition is abstract.

    The asynxhronous part is more that html can be loaded without having to follow a certain javascript structure in the traditional way. Whereas you could see it as a clock counting from: 00:00 to 24:00 , it`s the same with normal JS, however, the asynchronous part means, you can skip certain hours, or even better, there is no clock. You can do it asynchronous. For example, if you want 04:00, you normally had to wait 4 hours, with the asynchronous part, you dont, you can call it on the fly.

    That`s why its flexible. Off course, you are also right with your definition, that`s a “proper’ interpretation on whats going on. But i understand why Jerret would say it.
    Forgive me for my bad english, im not very good at it!

    With kind regards,
    Merijn

    • http://parkeffect.com Park
      Author

      I understand your point. It’s great! Thanks for sharing! And thanks for Jerret’s opinion too.

  • http://www.geekfirm.com Rocky

    I did not post any of these hateful comments so stop telling me to cailm down i have done nothing wrong, how i was i to know that my name was going to be tranished.

    Seroiusly a admin just deleted the comments (THAT I HAVE OUTLINED) as not being submit by me then no one else would have the chance to put there 5 cents in.

    • Global

      argghh again with the hate messages Rocky your hurting my ears! BTW Great tutorial

  • http://www.geekfirm.com Rocky

    I did not post any of the hateful comments displayed on this tutorial

    so stop telling me to cailm down i have done nothing wrong, how i was i to know that my name was going to be tranished.

    Seroiusly a admin just needs to delete all the comments (THAT I HAVE OUTLINED) as not being submit by me then no one else would have the chance to put there 5 cents in.

    I have already explained whats gone wrong

    * PS SORRY FOR THE SPAMMING OF THE COMMENTS I HAVE NO OTHER MEANS OF SORTING THIS ISSUE OUT OTHER THEN POSTING HERE AND HOPING THAT A ADMIN WILL AT LEST LOOK INTO THE SITUATION I DO NOT SEE THIS SITUATION BEING RESOLVED, AND I DO NOT DESERVE TO BE THE SUBJECT OF HATE

  • http://www.truedeity.com/ TrueDeity

    what would truedeity do?

  • http://butenas.com Ignas

    This is what I need right now! Thanks!

  • http://james.padolsey.com James

    Interesting. :)

    A couple of notes: XHR is not the same as Ajax. Ajax is a model for websites to follow, not a specific technology. Read up on it here: http://adaptivepath.com/ideas/essays/archives/000385.php

    The getJSON method isn’t Ajax, unless you use it for JSON on the same domain – for remote files it uses JSON-P (JSON “with padding”).

  • http://www.pathtosharepoint.com Christophe

    Nice post. Thanks for putting together the demo page and the Firebug walkthrough.

  • http://www.kamikazemusic.com Dave Sparks

    I’ve just started using Jquery for AJAX and the $post is a lot easier than some previous techniques I’ve used.
    Thanks for the round up it’ll certainly come in useful for more jquery/AJAX work

  • http://myfacefriends.com Myfacefriends

    another amazing tuts! thanks!

  • http://www.crearedesign.co.uk Martyn Web

    This has opened my eyes a bit, and I now actually know what its used for. Always here people talking about it and how good it is but never really decided to look in to it.

    Great tutorial for the beginner, thanks!

  • http://www.zachalig.com Zach

    God bless you. You just made me look good and a client of mine very happy!

  • http://michael.theirwinfamily.net Michael Irwin

    I do like using the $.ajax function. I actually just launched a new site that relies on it quite a bit. If anyone wants to check it out, it’s at http://www.hokietextbooks.com. If you want to test some sample CRN’s, some could be 97418 and 95300. Let me know what you think!

    Great tutorial!

  • Jean Azzopardi

    Nice tutorial, but a couple of things didn’t work for me, namely the load() Post and the load() JSON is only returning “” — even for relatively simple English phrases. The $.post() is also not working.

    I’m using Mozilla Firefox 3.5, btw

  • http://vijayjoshi.org Vijay Joshi

    Where is Rocky???

  • CHN

    I just say, this is a great explanation.
    Keep It Up.

  • http://www.geekfirm.com Rocky

    Omar Abid is worse then gorge bush!

    yea i posted all that stuff to make myself look bad!? idiot!!!!!!!!!!!!!!!!!!!!!

  • http://apcs.vn Hieu Vo

    Thx for giving me information about ajax calls besides $.ajax which I use very often.

  • ida

    This post is very useful

  • http://www.ajaxdump.com Jai

    Useful article for ajax beginners…

  • http://www.tlswebsolutions.com/ TLS Web Solutions

    This article was well written and very informative.
    The information is very clear and easy to understand even for the beginner.
    It is a crying shame that it has been littered with off subject comments.

  • Seven

    Personally I think that if you’re programming frequently that using one of the ajax functions would be best. The “ajax” function gives you the most flexibility. I know some will say they are all good, but the more you use pieces of code (and more important re-uses your own functions) you build libraries for further use.

    IMO pick one and stick with it, just my opinion.

  • http://www.huzaifaasif.co.uk Huzaifa Asif

    This article is awesome..Nice summary of the different JQuery AJAX functions. Well Done!!

  • Lochlan

    Didn’t know the bit about loading part of a remote file, very handy.

    How about if we’re using a $.post method? Can we load part of the remote file with that?