Hostingheaderbarlogoj
Join InMotion Hosting for $3.49/mo & get a year on Tuts+ FREE (worth $180). Start today.
Advertisement

jQuery Succinctly: jQuery and Ajax

by
Gift

Want a free year on Tuts+ (worth $180)? Start an InMotion Hosting plan for $3.49/mo.

This post is part of a series called jQuery Succinctly.
jQuery Succinctly: jQuery Effects

The jQuery ajax() Function is the Lowest-Level Abstraction

The jQuery ajax() function is the lowest level of abstraction available for XMLHttpRequests (aka AJAX). All the other jQuery AJAX functions, such as load(), leverage the ajax() function. Using the ajax() function provides the greatest functionality available for XMLHttpRequests. jQuery also provides other higher-level abstractions for doing very specific types of XMLHttpRequests. These functions are essentially shortcuts for the ajax() method.

These shortcut methods are:

The point to take away is that while the shortcuts are nice at times, they all use ajax() behind the scenes. And, when you want all the features and customizations that jQuery offers when it comes to AJAX, then you should just use the ajax() method.

Notes: By default, the ajax() and load() AJAX functions both use the GET HTTP protocol.


jQuery Supports Cross-Domain JSONP

JSON with Padding (JSONP) is a technique that allows the sender of an HTTP request, where JSON is returned, to provide a name for a function that is invoked with the JSON object as a parameter of the function. This technique does not use XHR. It uses the script element so data can be pulled into any site, from any site. The purpose is to circumvent the same-source policy limitations of XMLHttpRequest.

Using the getJSON() jQuery function, you can load JSON data from another domain when a JSONP callback function is added to the URL. As an example, here is what a URL request would look like using the Flickr API.

http://api.flickr.com/services/feeds/photos_public.gne?tags=resig&tagmode=all&format=json&jsoncallback=?

The ? value is used as a shortcut that tells jQuery to call the function that is passed as a parameter of the getJSON() function. You could replace the ? with the name of another function if you do not want to use this shortcut.

Below, I am pulling into a Web page, using the Flickr JSONP API, the most recent photos tagged with "resig." Notice that I am using the ? shortcut so jQuery will simply call the callback function I provided the getJSON() function. The parameter passed to the callback function is the JSON data requested.

<!DOCTYPE html>
<html lang="en">
<body>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script>  (function($){      
      $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=resig&amp;tagmode=all&amp;format=json&amp;jsoncallback=?",
          // Using ? just means call the callback function provided
          function (data) { // Data is the JSON object from Flickr    
              $.each(data.items, function (i, item) { $('<img />').attr("src", item.media.m).appendTo('body'); if (i == 30) return false; });
          });
  })(jQuery); </script>
</body>
</html>

Notes: Make sure you check the API of the service you are using for the correct usage of the callback. As an example, Flickr uses the name jsoncallback=? whereas Yahoo! and Digg use the name callback=?.


Stop a Browser From Caching XHR Requests

When doing an XHR request, Internet Explorer will cache the response. If the response contains static content with a long shelf life, caching may be a good thing. However, if the content being requested is dynamic and could change by the second, you will want to make sure that the request is not cached by the browser. One possible solution is to append a unique query string value to the end of the URL. This will ensure that for each request the browser is requesting a unique URL.

// Add unique query string at end of the URL
url: 'some?nocache='+(newDate()).getTime()

Another solution, which is more of a global solution, is to set up all AJAX requests by default to contain the no-cache logic we just discussed. To do this, use the ajaxSetup function to globally switch off caching.

$.ajaxSetup({
            cache: false // True by default. False means caching is off.
});

Now, in order to overwrite this global setting with individual XHR requests, you simply change the cache option when using the ajax() function. Below is a coded example of doing an XHR request using the ajax() function, which will overwrite the global setting and cache the request.

$.ajaxSetup ({   
    cache: false // True by default. False means caching is off.   
});       
jQuery.ajax({ cache: true, url: 'some', type: 'POST' } );
Advertisement