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
  • http://www.francescocruciani.com/ Francesco Cruciani

    Hi there!

    How can I applay an unique URL to my calls?

    • http://www.francescocruciani.com/ Francesco Cruciani

      window.location.href = newURL; ?
      but I don’t know how to use it…

    • http://www.balupton.com Benjamin “balupton” Lupton

      Sounds like your asking about using History/Hash-Change functionality. Check out the project and tutorial here, it sounds like it will be of use to you:
      http://www.balupton.com/sandbox/jquery-ajaxy

  • http://www.AbrahamBoray.tk AbrahamBoray

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

    ==> I’m Not Agree ,Well I think We can also Load the response ,by this Ajax function =)

  • http://www.russelluresti.com RussellUresti

    Is there any way to embed an absolute url into any of these options? All the examples I’ve seen use a relative path, like var loadUrl = “ajax/load.php”. Is there a way to make that var loadUrl = “http://whatever.com”? I’ve tried this, but I get an empty response back.

    • AlexGlover

      I was wondering the same thing. Any luck figuring it out?

      • http://noormohamed.co.uk Daniel

        You cant as jQuery wont allow cross domain requests like that. im sure if u poked about with the jquery.js theres a way to get around it :D

      • Namrata

        I am facing the same issue.
        What is the changes that need to be made to jquery.js to get external links to work here?

    • http://was.id.ly oyvindsk

      You can’t do that.. see http://en.wikipedia.org/wiki/Same_origin_policy

      You might be tempted to proxy it through your own domain, but you probably shouldn’t .. there are reasons the same origin policy is there in the first place..

  • http://www.blog.programmingtunes.com Altaf Hussain

    i was searching for such jquery scripts, and i found it here. Thanks for this tutorial.

  • http://URL(Optional) Aditu

    Hardly an article. Merely a few statements.

  • http://www.freelancer-id.com Alaa Al-Hussein

    Nice points. I think i should read this many times because i found few things explained well.

    I wish you the best, your writing was great.

  • Jikoyster

    I’m one of those who got ajax knowledge from this post. Thanks! You’re the man! Bookmark!

  • http://ro.botys.com Robotys

    Really a nice tuts. Learnt a lot from this.

    Got some problem while trying with this. Why my ajax didn`t load the processed variable (jquery (load/get/post)->php->mysql->php (html?) )

    Still trying from last night… hurmm.

  • http://www.umrah-haji.com Mister Ijoi

    Hi,

    Can anybody show me example for $.ajax() based on example above?

  • http://www.developersnippets.com Vivekanand

    This is one of the awesome article explained Ajax calls in details, thanks for your effort on this…. cheers!

    Thanks,
    Vivek

  • http://spotdex.com/ David Moreen

    For a long time now, I have been using $.ajax to call all ajax functions from jQuery, I would really like to try to use json a little bit more often now.

  • http://www.heshanj.info Heshan Peiris

    Good and valuable article

  • appaji

    its an excellent and awesome.
    it helps for the guys who start learning and hunting for samples.

  • Tuan Jinn

    Can someone please ban Mr. Rocky something out of this article. He and his disgraceful hating comments are very very inappropriate.

    Great article. I have been using Ajax and JQuery for a long time but still find article very interesting.

    Thanks

  • Aramtch

    Is there a way to dynamically pass the loadURL value to the script from the click event?

    ie. i have one button that i want to call “delete.php?file=one.jpg” and another button that I want to call “delete.php?file=two.jpg”.

    Anyone know if that’s possible? thanks.

  • chroot

    Rocky, everyone knows you did write that message so just admit it bro

  • http://www.indialike.com Indialike

    Very nice and useful tutorials for web designers,
    Thanks for posting.

  • http://www.e-sushi.net/ e-sushi

    I still have to decide what’s best about the article… the article itself (which is quite informative and good) or the flamewar comments that follow the article (which is quite amusing).

    Anyway, liked it in many ways. ;)

  • http://deluxe-site.com/ Diamond Deluxe

    Yeah, exactly what I needed to know since I’m currently developing my website and needed an ajax hint or two. Thank’s! Loving you for this article… guess I just found me next bookmark.

  • http:wwww.kumarphotography.com Mark Kumar

    Thank you soo much for sharing this. I’m new to jQuery and Ajax. So, I have been looking to some basic tutorial and your is very informative and to the point. Thanks for sharing. I will definitely use this on my site: http://www.kumarphotography.com.

    Mark Kumar

  • http://premiumpsd.com eyes drinker

    Thank you, this helped me out but i am still confused about the following, can you please help me??

    When i use

    $(“.rateit”).click(function(){
    $(this).next(“.rateoptions”).html(‘My options data here’);
    });

    It works smoothly, But when I use this in a callback function it doesn’t work as follow;

    $(“.rateit”).click(function(){
    $.get(“test.php”, function(data){
    $(this).next(“.rateoptions”).html(data);
    });
    });

    Thank you and looking forward

    • http://www.textpk.com eyes drinker

      OK, i solved it out, it can be used as follow

      $(“.rateit”).click(function(){
      var self=this;

      $.get(“test.php”, function(data){

      $(self).next(“.rateoptions”).html(data);

      });
      });

      just save “this” to a variable “self” and use it for reference.

  • Abin V Paul

    Hi, I am a php developer loves to work with Codeigniter and Kohana. This tutorial really made me confident enough to add more Ajax interactions in my projects. Thanks a lot…

  • kam
  • http://www.whatannoyedmetoday.com Zeeshan

    These days I am working on improving my jQuery skills and this article was very useful to understand these AJAX calls. However, I don’t understand how to replace .load() with something else. I have noticed that I post a variable to another page using .post, and then in the callback use another function to load another page using .load() which uses the earlier posted variable and assigns it further to a $_SESSION variable. But seems like this second page loads before the $_SESSION variable is set, so I still see the old information on the page. Now if I click F5 to refresh the page, only then I get the updated information. If I delay the load of the page through .load(), maybe it’ll fix this issue, but there must be a better way to do it. Any idea how?

  • http://www.MarkKumar.com Mark Kumar

    Thanks so much for sharing. I’ll be using it on: http://www.MarkKumar.com

    Mark

  • http://www.voipsystemscr.com Jose Tapia

    Thanks a lot for your explanation, :D great article

  • http://www.webchemie.nl Peter

    Thanks for this tutorial, really great!

  • sam

    Excellent

    I wanted to load a page from the Internet using jQuery’s.load function. But it loads all the texts except images. I need images also. What can I do?

    I tried as below -
    $(“#test”).load(“http://www.google.com”);

    It loads Google’s homepage but not the logo.

  • http://www.cmikavac.net pootzko

    this was very useful, made a few things crystal clear… thank you!

  • http://no-suelo.blogspot.com Albert Asensio

    Nice post.

    A detailed description how use JQuery and AJAX:

    http://no-suelo.blogspot.com/2010/09/calling-ajax-with-jquery.html

  • http://elainevellacatalano.com Elaine

    Thanks for this! Very useful and easy to follow :)

  • Azeem Michael

    brilliant!

  • http://www.drumcircle.info Jono Booth

    Awesome!! Thanks for putting this together!

  • http://www.brettwidmann.com Brett Widmann

    Great tutorial. Thanks for the info!

  • Patrick

    I’d like to use your script 1 but i have to call two page,so i’ve to write two variables.the Question is:before those variable how many Ajax false declaration i need to write?Only One or One for every variable (loadurl)? Thank you for answer,mauve stupid:)

  • claudio

    The demo does not work here in Firefox 3.6.13

  • http://www.badmintonconnect.com Badminton

    Short and concise, I’m bookmarking this for reference.

  • http://waqar-blog.blogspot.com Waqar

    Thanks, Wonderfully explained. I love this article

  • http://www.pixalwebdesign.com web design

    amazing tutorial…thanks for sharing this and i really support JQuery…

  • http://www.eddiemonge.com Eddie Monge

    You have a typo in the examples:

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

    There should be a space in the ” #DOM” part.

  • http://uptraffic.com uptraffic

    You mentioned code is not worked when i had used this in my website.

  • RedSpade

    I’m having an issue that I hope that perhaps you can steer me in the right direction.

    I’m using jQuery to animate a login-screen form pop-up. I enter my username/password combination and press submit on my form. A back-end PHP program is called, it reads the query_string value, parses the parameters, and calls a MySQL data table to authenticate the user. It then returns an “authorization level” value to the calling program. I can tell this is working correctly with judicious use of alert boxes.

    Now the tricky part. Once the div on the original form is populate with the authorization level value, the login-screen form toggles off (closes – disappears), however it is also removing my authorization level value. This puzzles me because it is far removed from the code around the pop-up form.

    Also I note that at this same time, the query_string values passed to the back-end PHP program are not appending to the URL of the calling program….. Do you have any thoughts you could share with a jQuery beginner?

  • http://ektaraval.blogspot.com/ Ekta

    It’s very useful. Thanks a lot for sharing…

  • http://www.RadioKDUG.com JFrankParnell

    Syntax:
    .load(loadUrl + ” #picture”);
    in the load_dom section. Apparently, the space between quote and #picture is necessary. Any hints as to why?

  • Imran

    I love this article, its awesome for learning. But if you explain $.ajax() also so it will make more convenient for full understanding.
    Thanks………………

  • http://www.juegosmil.com Juegos

    Great tutorial, I never use Json, but looks, very good. Thank you !

  • http://www.buyblackberry.info Onyx

    Great tutorial. after trying to use jquery, i have a bit trouble to populate the json result into a form automatically. Please, help me how to do that? thank you for helping.

  • http://www.shprint.ir چاپ

    Great tutorial.

  • ondiz

    But… When I use .get() method or other methods to update a div content the number of used DIV increase!
    I’ve tried with sIEve tool to monitor the number of #inUse DIVs.

    If I have a page with 10 second update interval after some minutes IE crash…

  • vishnu

    excellent article… especially the list of methods at the bottom and that table saying exactly what params can be passed to each method… there are so many methods for ajax in jQuery it can get confusing, but your information is a big help…