AJAX Methods - Appendices - Web Development with jQuery (2015)

Web Development with jQuery (2015)

Part IV. Appendices

Appendix G. AJAX Methods

Method

Description

Return Value

AJAX Requests

$.ajax([options])
$.ajax(url[, options])

Allows you to pass an object literal specifying various options in key, value pairs. For the complete list of options, see the “AJAX Options” table. This method is used by jQuery's other AJAX methods to make AJAX requests. You should use this method only if you require finer-grained control over an AJAX request than is possible with jQuery's other methods.

jQuery XMLHttpRequest

ajaxComplete(function())

Attaches a function to be executed when an AJAX request is completed.

jQuery

ajaxError(function())

Attaches a function that is executed when an error occurs.

jQuery

$.ajaxPrefilter(
[dataTypes],
function()
)

The dataTypes argument is optional and should contain one or more space-separated dataTypes.
The callback function argument sets default values for future AJAX requests. Its argument list is options, originalOptions, jqXHR.

Undefined

ajaxSend(function())

Attaches a function to be executed before an AJAX request is sent.

jQuery

$.ajaxSetup(options)

Configures the default options for AJAX requests. The option argument is passed as an object literal, in key, value pairs. See the “AJAX Options” table.

jQuery

ajaxStart(function())

Attaches a function to be executed when the first AJAX request begins (if not already active).

jQuery

ajaxStop(function())

Attaches a function to be executed when all AJAX requests have completed.

jQuery

ajaxSuccess(function())

Attaches a function to be executed when an AJAX request has completed successfully.

jQuery

$.ajaxTransport()

Creates the AJAX transport object used internally to issue AJAX requests. You should use this method only if you require finer-grained control over an AJAX request than is possible with jQuery's other methods.

undefined

$.get(
url
[, data]
[, onSuccessFunction]
[, dataType]
)

Initiates and sends to the server an HTTP GET request.

jQuery XMLHttpRequest

$.getJSON(
url
[, data]
[, function]
)

Initiates and sends an HTTP GET request, in which the response will be JSON-formatted data.

jQuery XMLHttpRequest

$.getScript(url, [function])

Loads and executes a new JavaScript file via the GET method asynchronously.

jQuery XMLHttpRequest

load(
url
[, data]
[, onCompleteFunction]
)

Loads HTML from a remote file and inserts the HTML inside of the selected elements. The data argument (optional) is specified as an object literal, defining the data you want to pass to the server in key, value pairs. Thefunction argument (also optional) is the callback method that handles the data when it is returned from the server.

jQuery

$.param(object[, traditional])

Creates a serialized representation of an object or an array, which can then be used in a URL or AJAX request.
The optional traditional argument indicates whether serialization should be a traditional shallow serialization.

String

$.post(
url
[, data]
[, onSuccessFunction]
[, dataType]
)

Initiates and sends to the server an HTTP POST request.

jQuery XMLHttpRequest

serialize()

Serializes a set of input elements into a string of data.

String

serializeArray()

Serializes all forms and form elements into a JSON structure.

Array

AJAX Options

Option

Description

Type

accepts

The content type sent in the request header to the server that tells the server what kind of response the browser can accept in its response.
The default value depends on dataType.

Object

async

By default, jQuery sends all AJAX requests asynchronously. To send a synchronous request, set this property to false.
Default value: true

Boolean

beforeSend

A callback function that is executed before the AJAX request is sent, which can be used to modify the jQuery XMLHttpRequest object, as well as to set custom headers. The arguments passed to this function are jqXHR andsettings.
Returning false from this function cancels the request.

Function

cache

If the value of the cache setting is set to false, the browser is forced to not cache the request.
The default value is true, false for dataType 'script' and 'jsonp'.

Boolean

complete

A function that is executed when the AJAX request has completed after the success or error callbacks have been executed.
This callback is passed two arguments: jqXHR and status.
The status argument will be any of the following strings: 'success', 'notmodified', 'error', 'timeout', 'abort', and 'parsererror'.

Function

contents

An object of string, regular expression pairs that determine how jQuery parses the server's response, given the specified dataType.

Object

contentType

The MIME type of data being sent to the server.
If a contentType is explicitly set, then it is always sent to the server.
The character set is defined as UTF-8 by the W3C specification. Using a different character set will not force the browser to change the encoding sent back to the server.
Default value:
application/x-www-form-urlencoded; charset=UTF-8

String

context

The object provided to this option is used to set the context of all AJAX-related callbacks.
Default value: an object used to call $.ajaxSettings() merged with the settings passed to $.ajax().

Object

converters

An object that specified dataType to dataType conversions. Each data type references a handler capable of processing that response.
Default value:
{
"* text" : window.String,
"text html" : true,
"text json" : $.parseJSON
"text xml" : $.parseXML
}

Object

crossDomain

Used to force or prevent a cross-domain request.
The default value is false for same-domain requests and true for cross-domain requests.

Boolean

data

The data to be sent to the server with a GET or POST request. Can be specified as either a string of ampersand-delimited arguments or as an object literal in key, value pairs. If the value is an Array, jQuery serializes based on the value of the traditional option.
Automatic processing of data can be modified with the processData option.

Object,
String,
Array

dataFilter

A callback function executed to handle the raw response data of XMLHttpRequest. This is a prefiltering function used to sanitize the response. You should return the sanitized data from this callback function. The function has two arguments: responseText and dataType.
function (responseText, dataType)
{
// do something
// return the sanitized // data
return data;
}

Function

dataType

The type of data that you expect to receive in your response from the server. jQuery attempts to automatically infer the dataType based on the MIME type of the data returned by the server.
See the “Data Types” table at the end of this appendix for a list of allowed data types.
Default value: Educated Guess

String

error

A callback function that is executed if the AJAX request fails.
The callback function has the following three arguments: jqXHR, errorType, and errorThrown.
The errorType argument can contain any of the following values: null, 'timeout', 'error', 'abort', and 'parsererror'.
The errorThrown argument contains the HTTP status if an HTTP error were thrown, such as "Not Found" or "Internal Server Error".

Function

global

Whether to trigger the global AJAX event handlers for the request, for example, the handlers set by the various AJAX Event methods.
Default value: true

Boolean

headers

An object of additional headers to include in the AJAX request. Headers should be specified in key, value pairs where the key is the name of the header, and the value is the header's value.
Default value: {}

Object

ifModified

Allows the request to be successful only if the request has been modified since the last request. This is determined by checking the time specified in the Last-Modified HTTP header.
Default value: false (ignore the Last-Modified header).

Boolean

isLocal

Allows the current environment to be recognized as a local environment. The following protocols are currently recognized by jQuery as being local: file, *-extension, and widget.
If this option requires modification, jQuery recommends doing so once in the $.ajaxSetup() method.

Boolean

jsonp

Overrides the callback function name in a jsonp request. This value will be used instead of 'callback' in the 'callback=?' part of the query string in the URL for a GET or POST request. So {jsonp:'onJsonPLoad'} would result in onJsonPLoad=? sent on to the server as part of the URL.

String

jsonpCallback

Used to specify a callback function for a JSONP request. The name specified here will be used instead of the randomly generated name created by jQuery for this purpose by default.

String,
Function

mimeType

A MIME type you want to use to override the default XHR MIME type.

String

password

A password to use in response to an HTTP access authentication request.

String

processData

By default, data passed in to the data option will be processed and transformed into a query string, fitting to the default content-type application/x-www-form-urlencoded; charset=URF-8. If you want to send DOMDocuments or other nonprocessed data, set this option to false.
Default value: true

Boolean

scriptCharset

For GET requests where the dataType is set to script or jsonp. Forces the request to be interpreted with the specified charset. This is needed only if the charset of local content is different from the remote content being loaded.

String

statusCode

An object of numeric HTTP codes and corresponding callback functions that should be called when that status code is encountered.
$.ajax({
statusCode : {
404 : function()
{
alert('URL not found.');
}
}
});

Object

success

A function that is executed upon success of the AJAX request.

Function

timeout

Sets the amount of time in milliseconds (ms) to allow before a timeout occurs.

Number

traditional

Determines how parameters for GET or POST requests will be serialized. If set to true, a shallow traditional serialization is used.

Boolean

type

The type of HTTP request, one of GET or POST. You can also specify PUT or DELETE. However, those methods are not supported by all browsers.

String

url

The URL to request.

String

username

A username to specify in response to an HTTP authentication required request.

String

xhr

Callback for creating the XMLHttpRequest object. Defaults to the ActiveXObject when available (IE), the XMLHttpRequest otherwise. Override to provide your own implementation for XMLHttpRequest or enhancements to the factory.

Function

xhrFields

An object of key, value pairs that should be set on the native XMLHttpRequest object.

Object

Data Types

Type

Description

xml

Returns an XML document that can be processed with jQuery.

html

Returns HTML as plain text. <script> elements are evaluated upon insertion into the DOM.

script

Evaluates the response as JavaScript and returns the script as plain text to the callback function. Disables caching unless the cache option is used. Note: This type of request will make POST requests into GET requests.

json

Evaluates the response as JSON and returns a JavaScript object.

jsonp

Loads in a JSON block using JSONP. Adds an extra ?callback=? to the end of your URL to specify the callback.

text

Returns the server response as a plain text string.

multiple, space-separated values

Converts what jQuery received in the Content-Type header to what you require. For example, to text a text response and treat it like XML, the value "text xml" should be used. In addition, it is possible to send a JSONP request, receive the response as text, and then interpret the response as XML, which would be done using the value "jsonp text xml".