jQuery.ajaxSetup()S2C Home « Ajax « jQuery.ajaxSetup()

Initialize default Ajax settings.

Description

The jQuery.ajaxSetup() Ajax method, allows us to initialize default settings for future Ajax requests.

Shorthand version $.ajaxSetup()

  • All subsequent Ajax requests using any function will use the new settings, unless overridden by the individual requests, until the next invocation of $.ajaxSetup().

Syntax


Signature Description
jQuery.ajaxSetup( settings )Initialize default settings for future Ajax requests.

Parameters


Parameter Description
settings Default settings can be set globally by using the jQuery.ajaxSetup() method but the settings below can be useful for individual Ajax requests.

Optional set of key/value pairs that configure the Ajax request.Type
  • acceptsPlainObject
    Default: depends on DataType
    The content type sent in the request header which informs the server what kind of response it will accept on return.
    • If the accepts setting needs modifying, do this once in the jQuery.ajaxSetup() method.
  • asyncBoolean
    Default: true
    If you need synchronous requests this can be achieved by setting this option to false:
    • Synchronous requests by their nature may lock the browser, temporarily disabling any actions while the request is active.
    • Cross-domain requests and requests using the jsonp dataType do not support synchronous operation.
    • From jQuery version 1.8, using async: false is deprecated, so best to avoid using this setting altogether and let it default.
  • beforeSend(jqXHR, settings)Function
    A pre-request callback function that can be used to modify the jqXHR and will be called regardless of the type of request:
    • The jqXHR object and settings s are passed as arguments.
    • if the beforeSend() function returns false it will cancel the $.ajax()request.
    • Use this to set customized headers and such.
    • This is an Ajax Event.
  • cacheBoolean
    Default: false for dataTypes jsonp and script | true for all other dataTypes
    When set to false:
    • Requested pages will not be cached by the browser.
    • Appends a query string parameter, "_=[TIMESTAMP]", to the URL.
  • complete(jqXHR, textStatus)Function(s)
    A function or an array of functions, where each function gets called in turn, to be called when success and fail callbacks have executed and the request has finished:
    • The jqXHR object and a string categorizing the status of the request ( "abort", "error", "notmodified", "parsererror", "success" or "timeout") are passed as arguments.
    • This is an Ajax Event.
    • This is callback hook which is a first-in, first-out managed queue and as such can assign more than one callback for each hook. See the lesson on the Deferred object and methods, which are implemented internally for these jQuery.ajaxSetup() callback hooks, for an explanation of the mechanics and how to use deferreds.
    • When the request finishes 'completeCallbacks' fire in the order they were registered, whether 'error' or 'success'.
  • contentsPlainObject
    An object of string/regular-expression pairs determining how jQuery will parse the response, given its content type.
  • content-typeString
    Default: 'application/x-www-form-urlencoded'
    Sets the content type for data being sent to the server and the default is fine for most situations:
    • If you explicitly pass in content-type to the $.ajax() method it will always be sent to the server, regardless of any data being sent.
    • Data is always transmitted to the server using the UTF-8 charset and you must decode this appropriately on the server side.
  • contextObject
    An object to be made the context for all Ajax-related callbacks:
    • By default, the context is an object representing any ajax settings passed to the jQuery.ajax method merged with those setup from the jQuery.ajaxSetup() method.
  • convertersPlainObject
    Default: {"* text": window.String, "text html": true, "text json": jQuery.parseJSON, "text xml": jQuery.parseXML}
    An object of dataType-to-dataType converters.
    • Each converter's value is a function that returns the transformed value of the response.
  • crossDomainBoolean
    Default: false for same-domain requests | true for cross-domain requests.
    • If you wish to force a crossDomain request on the same domain, set the value of crossDomain to true.
  • dataObject or String
    Data to be sent to the server:
    • For objects, the object must consist of Key/Value pairs. If the value is an array, jQuery will serialize multiple values with the same key based on the value of the traditional setting which is described below for that setting. This processing can be circumvented by setting the processData option to false. The processing might be undesirable if you wish to send an XML object to the server; in this case, change the contentType option from application/x-www-form-urlencoded to a more appropriate MIME type.
    • For anything else, if not already a string the data gets converted to a query string and is appended to the url for GET-requests. This processing can be circumvented by setting the processData option to false.
  • dataFilter(data, type)Function
    Function used to handle the raw response data of a XMLHttpRequest:
    • The function accepts two arguments, the raw data as returned from the server and the dataType parameter.
    • This is a pre-filtering function to sanitize the response and the sanitized data will be passed on to the
      done(data, textStatus, jqXHR) callback function.
  • dataTypeString
    Default: Inferred based on the MIME type of the response (html, json, script, or xml)
    A string value or multiple, space-separated string values specifying the type of data that you're expecting back from the server. Ensure that the MIME type reported by the web server matches your choice of dataType.

    The jQuery.ajaxSetup() method relies on the server to provide information about the retrieved data. If the server reports the return data as XML, the result can be traversed using normal XML methods or jQuery's selectors. If another type is detected the data is treated as text but different data handling can be achieved using the dataType settings as outlined below:

    • "html": Returns HTML as a plain text string after executing any embedded JavaScript inside the retrieved data.
    • "json": Evaluates the response as JSON and returns a JavaScript object as the result data. This is achieved using the jQuery.parseJSON() method when the browser supports it or a Function constructor otherwise. Malformed JSON data will throw a parse error as detailed here: json.org site. If the fetched data file exists on a remote server, specify the jsonp type instead.
    • "jsonp": Loads in a JSON block using JSONP. Adds an extra "?callback=?" to the end of the URL to specify the callback. Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to the URL unless the cache option is set to true. The server should prepend the JSON data with the callback name to form a valid JSONP response. We can specify a parameter name other than callback when using the jQuery.ajaxSetup() method by using the jsonp setting as described under the setting parameters below. JSONP is an extension of the JSON format, requiring some server-side code to detect and handle the query string parameter. When data is retrieved from remote servers, any error callbacks and global events will never be fired.
    • "script": Executes the JavaScript that is pulled back from the server and then returns nothing. When data is retrieved from remote servers, any error callbacks and global events will never be fired.
    • "text": Returns a plain text string with no processing. The data is simply passed on to the success handler through the responseText property of the jqXHR object.
    • "xml": Returns a XML document with no processing that can be processed via jQuery. The data is simply passed on to the success handler through the responseXML property of the jqXHR object. XML must be declared by the server as text/xml or application/xml for consistent results.
    • Multiple space-separated string values will notify a value to receive and how that value is intepreted. For example "jsonp text xml" equates to make a JSONP request, have it received as text, and interpreted by jQuery as XML.
  • error(jqXHR, textStatus, errorThrown)Function(s)
    A function or an array of functions, where each function gets called in turn:
    • The jqXHR object, a string categorizing the status of the request ( "abort", "error", "null", "parsererror", "success" or "timeout") and an optional exception object, if one occurred, are passed as arguments.
    • This handler is not called for cross-domain script and jsonp requests.
    • This is an Ajax Event.
    • This is callback hook which is a first-in, first-out managed queue and as such can assign more than one callback for each hook. See the lesson on the Deferred object and methods, which are implemented internally for these jQuery.ajaxSetup() callback hooks, for an explanation of the mechanics and how to use deferreds.
    • When the request finishes 'errorCallbacks' fire in the order they were registered.
  • globalBoolean
    Default: true
    Whether to trigger global Ajax event handlers for this request.
    • Setting this to false will prevent the global Ajax event handlers from triggering for this request.
  • headersPlainObject
    Default: {}
    An object of additional header key/value pairs to send along with the request:
    • Set before the beforeSend() function is called and so any values modified with this setting can be overwritten from within the beforeSend() function.
  • ifModifiedBoolean
    Default: false
    Allow the request to be successful only if the response has changed since the last request.
    • Setting this to true will check the Last-Modified header to see if the asset has been modified since the last request.
  • isLocalBoolean
    Default: dependant upon current location protocol
    Allow the current environment (the filesystem) to be recognized as "local," even if jQuery doesn't recognize it as such by default.
    • The following protocols are currently recognized as local: file, *-extension, and widget.
    • If the isLocal setting needs modifying, do this once in the jQuery.ajaxSetup() method.
  • jsonpString
    Override 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.
    • Setting the jsonp option to false prevents jQuery from adding the 'callback=?' string to the URL or attempting to use "=?" for transformation. In this scenario, the jsonpCallback setting should also be explicitly set. For example, { jsonp: false, jsonpCallback: "callbackName" }.
  • jsonpCallbackString or Function
    Specify the callback function name for a jsonp request:
    • This value will be used instead of the random name automatically generated by jQuery although it is preferable to let jQuery generate a unique name to make it easier to manage the requests, provide callbacks and error handling.
    • You may want to specify the callback name using jsonpCallback when you want to enable better browser caching of GET requests.
    • If you use a function to set the value of jsonpCallback, it will be set to the return value of that function.
  • mimeTypeString
    A mime type to override the XHR mime type.
  • passwordString
    A password to be used in response to an HTTP access authentication request.
    If the server performs HTTP authentication before providing a response, the user name and password pair can be sent via the username and password options.
  • processDataBoolean
    Default: true
    By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded".
    • Setting this option to false allows sending of a DOMDocument, or other non-processed data.
  • scriptCharsetString
    Forces the request to be interpreted as a certain charset:
    • Only pertinent for requests with "jsonp" or "script" dataType and "GET" type.
    • Only required for charset differences between the remote and local content.
  • statusCodePlainObject
    Default: {}
    An object of numeric HTTP codes and functions to be called when the response has the corresponding code:
    • If the request is successful, the status code functions take the same parameters as the done callback.
    • If the request fails, the status code functions take the same parameters as the fail callback.
  • success(data, textStatus, jqXHR)Function(s)
    A function or an array of functions, where each function gets called in turn, that is called if the request succeeds:
    • The function gets passed three arguments, the data returned from the server formatted according to the dataType parameter, a string describing the status and the jqXHR object.
    • This is an Ajax Event.
    • This is callback hook which is a first-in, first-out managed queue and as such can assign more than one callback for each hook. See the lesson on the Deferred object and methods, which are implemented internally for these jQuery.ajaxSetup() callback hooks, for an explanation of the mechanics and how to use deferreds.
    • When the request finishes 'successCallbacks' fire in the order they were registered.
  • timeoutNumber
    Set a timeout (in milliseconds) for the request:
    • The timeout period starts at the point when the jQuery.ajax call is made and in certain scenarios it is possible for a request to time out before it can be sent.
    • Using the timeout setting will override any global timeout set with the jQuery.ajaxSetup() method, but this is not recommended for specific requests.
  • traditionalBoolean
    Set this to true if you wish to use the traditional style of param serialization as used by the
    jQuery.param( obj, traditional ) method signature.
  • typeString
    Default: 'GET'
    The type of request to make ('POST' or 'GET'):
    • Ajax requests default to being sent using the 'GET' HTTP method. If the 'POST' method is required, this can be specified by setting a value using the type setting. The type setting affects how the contents of the data option are sent to the server. POST data will always be transmitted to the server using UTF-8 charset, as per the W3C XMLHTTPRequest standard.
    • Other HTTP request methods besides 'POST' and 'GET' can also be used, but are not supported in all browsers.
  • urlString
    Default: The current page
    A string containing the URL to which the request is to be sent.
  • usernameString
    A password to be used in response to an HTTP access authentication request.
    If the server performs HTTP authentication before providing a response, the user name and password pair can be sent via the username and password options.
  • xhrString
    Default: ActiveXObject when available (IE), the XMLHttpRequest otherwise
    Callback for creating the ActiveXObject / XMLHttpRequest object:
    • Override to provide your own implementation for ActiveXObject / XMLHttpRequest or enhancements to the factory.
  • xhrFieldsPlainObject
    An object of fieldName-fieldValue pairs to set on the native XHR object.

Return

None.

jQuery.ajaxSetup( settings ) Examplesgo to top of page Top

Initialize default settings for future Ajax requests.

In the example below when we press the left button we create an Ajax request, passing the complete() callback function. The only output we see is from this callback as the request has no settings for the request apart from this.

In the example below when we press the right button the first time we create some settings for url and dataType using the $.ajaxSetup() method. If we then press the left button after this our request works as can be seen from the output messages. This is because the request will use the settings we created using the $.ajaxSetup() method for the url and dataType settings and therefore have enough information to successfully complete the request.


$(function(){
  $('#btn5').on('click', function(){
    $.ajax({
      complete: function() { 
        $('#div1').append('The request ended! <br />');
      }
    });
  });
  $('#btn6').one('click', function(){
    $.ajaxSetup({
      url: "../js/get1.js", 
      dataType: "script"
    });
  });
});

/*
 * The code for the external Javascript file called from $.ajax() (url: "../js/get1.js")
 * is shown below.
 */
$(function(){
  var someText = 'Passing some text. ';
  $('#div1').append('Message from get1.js: ' + someText + '<br />');
});

div1. Some initial text.

Press the button below to action the above code:

               



go to home page Homepage go to top of page Top