AJAX

The ajax() method is general method to perform an asynchronous HTTP request. Other methods are shorthand of ajax() method.

Except load(), methods return the jqXHR object.

$.get( "ajax/test.html", function(data) {
  $(".result").html(data);
  alert( "Load was performed." );
});

// load content of ajax/test.html into #result element
$( "#result" ).load( "ajax/test.html" );

// out: width=1680&height=1050
console.log($.param({ width:1680, height:1050 }));

// out something like: 
// single=Single&multiple=Multiple&multiple=Multiple3&check=check2&radio=radio1
$("form").on("submit", function(event) {
  event.preventDefault();
  console.log($(this).serialize());
});
more examples
method description
ajax(url [, opt])

Perform an asynchronous HTTP request. The opt parameter contains the request setting object.

ajax([opt])

Perform an asynchronous HTTP request. The opt parameter contains the request setting object.

get(url [, data] [, opt] [, cbOk ] [, dataType ])

Load data from the server using a HTTP GET request. The opt parameter contains the request setting object.

post(url [, data] [, opt] [, cbOk ] [, dataType ])

Send data to the server using a HTTP POST request. The opt parameter contains the request setting object.

getJSON(url [, data ] [, cbOk ] ) Load JSON-encoded data from the server using a GET HTTP request.
getScript(url [, cbOk ] ) Load a JavaScript file from the server using a GET HTTP request, then execute it.
load(url [, data ] [, cbComplete ] ) Load data from the server and place the returned HTML into the matched elements. This method return jQuery object.
param(obj ) Creates a serialized representation of an array, a plain object, or a jQuery object suitable for use in a URL query string or Ajax request.
serialize() Encodes a set of form elements as a string for submission. Form elements can be selected, for example $("#myform"), or you can specify individual form controls, for example $("input, textarea, select").

callbacks

There are several ways to assign a request callbacks using.

  • jqXHR object
  • request settings
  • global ajax event handlers
$.ajax("example.php", { // callbacks in request settings
  success: function(response) {
         alert( "success" );
    }
  statusCode: {
    404: function() {
      alert( "page not found" );
    }
  }
}).always(function() { // assign callback in jqXHR object
    alert( "complete" );
  });

Below ajax callback specifications.

field description
cbOk(data, txtStatus, jqXHR) A callback function that will be called when the request is successful.
cbErr(jqXHR, txtStatus, txtErr) A callback function that will be called when the request fails.
cbComplete(jqXHR, txtStatus) A callback function that will be called when the request finishes. The txtStatus parameter can have following values:
  • success
  • notmodified
  • nocontent
  • error
  • timeout
  • abort
  • parsererror
cbBeforeSend(jqXHR, opt) A pre-request callback function that can be used to modify the jqXHR. This is used to set custom headers, etc.

request settings

Ajax settings are represented as a PlainObject type object. Most usefull fields are listed below.

field description
url A string containing the URL to which the request is sent.
type The HTTP method to use for the request (e.g. "POST", "GET", "PUT"). An alias for method. You should use type if you're using versions of jQuery prior to 1.9.0.
contentType The type of data being sent. Default value is 'application/x-www-form-urlencoded; charset=UTF-8'. Specification dictates that the charset is always UTF-8, so specifying another charset will not force the browser to change the encoding.
data The PlainObject or String or Array object that specifies data to be sent to the server. If the HTTP method is one that cannot have an entity body, such as GET, the data is appended to the URL.
dataType The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response. Possible values:
  • xml - XML document that can be processed via jQuery
  • html - HTML as plain text; included script tags are evaluated when inserted in the DOM.
  • script - evaluates the response as JavaScript and returns it as plain text
  • json - evaluates the response as JavaScript and returns it as plain text
  • jsonp - loads in a JSON block using JSONP. Adds an extra "?callback=?" to the end of your URL to specify the callback.
  • text - a plain text string

You can use multiple, space-separated values. For example "jsonp xml" will first attempt to convert from jsonp to xml, and, failing that, convert from jsonp to text, and then from text to xml.

headers An object of additional header key/value pairs to send along with requests. Default value is {}.
username A username to be used with XMLHttpRequest in response to an HTTP access authentication request.
password A password to be used with XMLHttpRequest in response to an HTTP access authentication request.
timeout Set a timeout (in milliseconds) for the request. A value of 0 means there will be no timeout.
async The default is true, which means that all requests are sent asynchronously. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation.
cache If set to false, it will force requested pages not to be cached by the browser. Setting cache to false will only work correctly with HEAD and GET requests. Default value is true and false for dataType 'script' and 'jsonp'.
contents An object of string/regular-expression pairs that determine how jQuery will parse the response, given its content type.
context Specifies a context for callback functions. By default, the context is an object that represents the Ajax settings used in the call. You can use DOM element as the context
$.ajax({
  url: "test.html",
  context: document.body
}).done(function() {
  $( this ).addClass( "done" );
});
crossDomain Default value is false for same-domain requests and true for cross-domain requests. If you wish to force a crossDomain request (such as JSONP) on the same domain, set the value of crossDomain to true. This allows, for example, server-side redirection to another domain.
success A callback function that will be called when the request is successful.
error A callback function that will be called when the request fails.
complete A callback function that will be called when the request finishes. From jQuery 1.5 the complete setting can accept an array of functions.
beforeSend A pre-request callback function that can be used to modify the jqXHR. This is used to set custom headers, etc.
statusCode Object with callbacks for HTTP codes.

jqXHR

The ajax methods return jqXHR object - the instance of jQuery XMLHttpRequest class. It wraps the browser's native XMLHttpRequest object and implements Promise interface.

Below some extra methods of jqXHR.

method description
done(cbOk) Adds a successful callback. If the request has already completed with a successful state, the callback will be executed immediately.
fail(cbErr) Adds an error callback. If the request has already completed with a failed state, the callback will be executed immediately.
then(cbOk, cbErr) Incorporates the functionality of the done() and fail() methods.
always(cbComplete) Adds an complete callback. If the request has already completed, the callback will be executed immediately.