Jquery ajax utility function - $.ajax()

 

For those times when we want or need to exert a fine-grained level of control over how we make Ajax requests, jQuery provides a general utility function for making Ajax requests named $.ajax(). Under the covers, all other jQuery features that make Ajax requests eventually use this function to initiate the request.

$.ajax(options)

Initiates an Ajax request using the passed options to control how the request is made and callbacks notified.

Parameters

options (Object)     An object instance whose properties define the parameters to this operation.

 

Looks simple, doesn’t it? But don’t be deceived. The options parameter can specify a large range of values that can be used to tune the operation of this function. These options (in order of the likelihood of their use) are defined in the table:



Options for the $.ajax() utility function

Name Type Description
url String The URL for the request.
type String An object whose properties serve as the query parameters to be passed to the request. If the request is a GET, this data is passed as the query string. If a POST, the data is passed as the request body. In either case, the encoding of the values is handled by the $.ajax() utility function.
dataType String A keyword that identifies the type of data that’s expected to be returned by the response. This value determines what, if any, post-processing occurs upon the data before being passed to callback functions. The valid values are as follows:
  • xml—The response text is parsed as an XML document and the resulting XML DOM is passed to the callbacks.
  • html—The response text is passed unprocessed to the callbacks functions. Any 'script' blocks within the returned HTML fragment are evaluated.
  • json—The response text is evaluated as a JSON string, and the resulting object is passed to the callbacks.
  • jsonp—Similar to jason except that remote scripting is allowed, assuming the remote server supports it.
  • script—The response text is passed to the callbacks. Prior to any callbacks being invoked, the response is processed as a JavaScript statement or statements.
  • text—The response text is assumed to be plain text.

The server resource is responsible for setting the appropriate content-type response header. If this property is omitted, the response text is passed to the callbacks without any processing or evaluation.

timeout Number Sets a timeout for the Ajax request in milliseconds. If the request does not complete before the timeout expires, the request is aborted and the error callback (if defined) is called.
global Boolean Enables (if true) or disables (if false) the triggering of so-called global functions. These are functions that can be attached to elements that trigger at various points or conditions during an Ajax call. We’ll be discussing them in detail in section 8.8. If omitted, the default is to enable the triggering of global functions.
contentType String The content type to be specified on the request. If omitted, the default is application/x-www-form-urlencoded, the same type used as the default for form submissions.
success Function A function invoked if the response to the request indicates a success status code. The response body is returned as the first parameter to this function and formatted according to the specification of the dataType property. The second parameter is a string containing a status value—in this case, always success.
error Function A function invoked if the response to the request returns an error status code. Three arguments are passed to this function: the XHR instance, a status message string (in this case, always error), and an optional exception object returned from the XHR instance.
complete Function A function called upon completion of the request. Two arguments are passed: the XHR instance and a status message string of either success or error. If either a success or error callback is also specified, this function is invoked after the callback is called.
beforeSend Function A function invoked prior to initiating the request. This function is passed the XHR instance and can be used to set custom headers or to perform other pre-request operations.
async Boolean If specified as false, the request is submitted as a synchronous request, By default, the request is asynchronous.
processData Boolean If set to false, prevents the data passed from being processed into URLencoded format. By default, the data is URL-encoded into a format suitable for use with requests of type application/x-www-form-urlencoded.
ifModified Boolean If true, allows a request to succeed only if the response content has not changed since the last request according to the Last-Modified header. If omitted, no header check is performed.

 

Examples:

Load and execute a JavaScript file.

    	$.ajax({
          type: "GET",
          url: "test.js",
          dataType: "script"
        });
    

Save some data to the server and notify the user once its complete.

    	$.ajax({
           type: "POST",
           url: "some.php",
           data: "name=John&location=Boston",
           success: function(msg){
             alert( "Data Saved: " + msg );
           }
         });
    

Retrieve the latest version of an HTML page.

	$.ajax({
      url: "test.html",
      cache: false,
      success: function(html){
        $("#results").append(html);
      }
    });

Loads data synchronously. Blocks the browser while the requests is active. It is better to block user interaction by other means when synchronization is necessary.

    	var html = $.ajax({
          url: "some.php",
          async: false
         }).responseText;
    

Sends an xml document as data to the server. By setting the processData option to false, the automatic conversion of data to strings is prevented.

	 var xmlDocument = [create xml document];
         $.ajax({
           url: "page.php",
           processData: false,
           data: xmlDocument,
           success: handleResponse
         });
Add your comment 1 Comments

S

2011-04-27 07:13:49


good job!

Post your opinion


Post your message and we'll contact you immediately.
Thank you for your desire to work with us.

Please, fill out the required fields!

Close
OK