You are on page 1of 11

2/13/2011

5WaystoMakeAjaxCallswithjQue

Advertise Here

5 Ways to Make Ajax Calls with jQuery


Piao Yishi on Aug 18th 2009 with 115 comments

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, well line them up and make a comparison. Additionally. well 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 dont 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, its the same thing. Dont 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 thats 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.
tutsplus.com//5-ways-to-make-a 1/11

2/13/2011

5WaystoMakeAjaxCallswithjQue

The key to AJAXs concept is asynchronous. This means something happens to the page after its 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 Gmails 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 seconds time, caching AJAX becomes a bug, right? It should be noted that Internet Explorer always caches AJAX calls, while other browsers behave differently. So wed better tell the browser explicitly whether or not AJAX should be cached. With jQuery, we can accomplish this simply by typing: view plaincopy to clipboardprint? 1. $.ajaxSetup ({ 2. cache: false 3. });

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 jQuerys load() function, this task is a piece of cake. Review this demo and well 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. Lets see whats going on behind the scenes. Below is the JavaScript code for this effect: view plaincopy to clipboardprint? 1. 2. 3. 4. 5. 6. // $.ajaxSetup ({ cache: false }); var ajax_load = "<img src='img/load.gif' alt='loading...' />"; load() functions
2/11

tutsplus.com//5-ways-to-make-a

2/13/2011

5WaystoMakeAjaxCallswithjQue

7. 8. 9. 10.

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, its 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). Cant be more straightforward, hah? Now, lets explore more details of the request with Firebug: 1. Open Firebug. 2. Switch to the Net tab. Enable it if its disabled. This is where all HTTP request in the browser window are displayed. 3. Switch to XHR tab below Net. Remember the term XHR? Its 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. Heres 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. Heres the HTML response returned from the remote url.

tutsplus.com//5-ways-to-make-a

3/11

2/13/2011

5WaystoMakeAjaxCallswithjQue

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: view plaincopy to clipboardprint? 1. $("#load_dom").click(function(){ 2. $("#result") 3. .html(ajax_load) 4. .load(loadUrl + " #picture"); 5. }); 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. view plaincopy to clipboardprint? 1. $("#load_get").click(function(){ 2. $("#result") 3. .html(ajax_load) 4. .load(loadUrl, "language=php&version=5"); 5. }); By passing a string as the second param of load(), these parameters are passed to the remote url in the GET method. In
tutsplus.com//5-ways-to-make-a 4/11

2/13/2011

5WaystoMakeAjaxCallswithjQue

Firebug, these params are shown as follows:

Pass Parameters Through the POST Method


Click on the load() POST button and open Firebug. view plaincopy to clipboardprint? 1. $("#load_post").click(function(){ 2. $("#result") 3. .html(ajax_load) 4. .load(loadUrl, {language: "php", version: 5}); 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. view plaincopy to clipboardprint?
tutsplus.com//5-ways-to-make-a 5/11

2/13/2011

5WaystoMakeAjaxCallswithjQue

1. $("#load_callback").click(function(){ 2. $("#result") 3. .html(ajax_load) 4. .load(loadUrl, null, function(responseText){ 5. alert("Response:\n" + responseText); 6. }); 7. }); 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 well review the second AJAX method in jQuery. JSON (JavaScript Object Notation) is a lightweight data-interchange format. Its very convenient when exchanging data programmatically with JSON. Lets review an example. Find the $.getJSON() section in the demo page, type in some words in your native language, and click detect language. view plaincopy to clipboardprint? 1. // $.getJSON() 2. var jsonUrl = "ajax/json.php"; 3. $("#getJSONForm").submit(function(){ 4. var q = $("#q").val(); 5. if (q.length == 0) { 6. $("#q").focus(); 7. } else { 8. $("#result").html(ajax_load); 9. $.getJSON( 10. jsonUrl,
tutsplus.com//5-ways-to-make-a 6/11

2/13/2011

5WaystoMakeAjaxCallswithjQue

11. 12. 13. 14. 15. 16. 17. 18. 19.

{q: q}, function(json) { var result = "Language code is \"<strong>" + json.responseData.language + "\""; $("#result").html(result); } ); } return false; });

Lets jump to Line 9: 1. $.getJSON doesnt 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. $.getJSONs function name is NOT camel-cased. All four letters of JSON are in uppercase. Look at the response in JSON format in Firebug. Its 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; lets review the code for this action. view plaincopy to clipboardprint? 1. // $.getScript() 2. var scriptUrl = "ajax/script.php"; 3. $("#getScript").click(function(){ 4. $("#result").html(ajax_load); 5. $.getScript(scriptUrl, function(){ 6. $("#result").html(""); 7. }); 8. }); 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 dont 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.
tutsplus.com//5-ways-to-make-a 7/11

2/13/2011

5WaystoMakeAjaxCallswithjQue

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. view plaincopy to clipboardprint? 1. // $.get() 2. $("#get").click(function(){ 3. $("#result").html(ajax_load); 4. $.get( 5. loadUrl, 6. {language: "php", version: 5}, 7. function(responseText){ 8. $("#result").html(responseText); 9. }, 10. "html" 11. ); 12. }); 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 its 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. view plaincopy to clipboardprint? 1. // $.post() 2. $("#post").click(function(){ 3. $("#result").html(ajax_load); 4. $.post( 5. loadUrl, 6. {language: "php", version: 5}, 7. function(responseText){ 8. $("#result").html(responseText); 9. }, 10. "html"
tutsplus.com//5-ways-to-make-a 8/11

2/13/2011

5WaystoMakeAjaxCallswithjQue

11. 12.

); });

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, weve 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 jQuerys low-level AJAX implementation. See $.get, $.post etc. for higher-level abstractions that are often easier to understand and use, but dont offer as much functionality (such as error callbacks). jQuerys 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 dont 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, heres a comparison table of these functions. I hope you enjoyed this lesson! Any thoughts?

Follow us on Twitter, or subscribe to the NETTUTS RSS Feed for more daily web development tuts and articles.
Like 51 people like this. Be the first of your friends.

tutsplus.com//5-ways-to-make-a

9/11

2/13/2011

5WaystoMakeAjaxCallswithjQue

Piao Yishi is park on Tutsmarketplace

By Piao Yishi
Piao Yishi (aka Park) is a web developer from Hangzhou, the most beautiful city in China. He loves jQuery and CakePHP. Hes passionate about building websites that make this world a better place to live.
tutsplus.com//5-ways-to-make-a 10/11

2/13/2011

5WaystoMakeAjaxCallswithjQue

tutsplus.com//5-ways-to-make-a

11/11

You might also like