Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 56 ยท AJAX

AJAX with $.ajax()

Learn jQuery $.ajax(): the settings object, method, data, dataType, success and error callbacks, statusText, headers, timeout and contentType, with runnable examples.

AJAX means asking a server for data from JavaScript, without reloading the page, and then updating part of the page with the answer. Search suggestions, "load more" buttons, live form checks and chat boxes all work this way. jQuery's low-level tool for it is $.ajax(). Every other AJAX helper in the library, such as $.get() and .load(), is a thin wrapper around it, so understanding $.ajax() means understanding all of them.

One practical problem: the examples in this course run in a sandbox that cannot reach a real server. To keep every example runnable, each one installs a few lines that stand in for a server and answers requests whose URL starts with /api/. The stand-in plugs in below the request layer, so everything above it, the settings, callbacks and status handling, is exactly the jQuery code you would write against a real server. On your own site, delete the stand-in block and nothing else changes.

Anatomy of a request

Request URL, method, data, headers.
Server Replies with a status and a body.
Response jQuery parses it by dataType.
Callbacks success, error, complete.
1 / 2

The settings object

$.ajax() takes one object. Only url is required; everything else has a default.

JavaScript
$.ajax({
  url: "/api/users/1",
  method: "GET",
  dataType: "json",
  timeout: 5000,
  success: function (data, textStatus, jqXHR) {
    console.log(data.name);
  },
  error: function (jqXHR, textStatus, errorThrown) {
    console.log(textStatus, errorThrown);
  },
  complete: function (jqXHR, textStatus) {
    console.log("finished with", textStatus);
  }
});

The most useful settings:

Setting Meaning
url Where to send the request.
method "GET" (default), "POST", "PUT", "DELETE" and so on. type is the older alias.
data Object, string or array to send. For GET it becomes the query string; for POST it goes in the body.
dataType What you expect back: "json", "html", "text", "xml", "script". If omitted, jQuery guesses from the response's Content-Type.
contentType Format of the body you send. Default application/x-www-form-urlencoded; charset=UTF-8.
headers Extra request headers as an object.
timeout Milliseconds before the request is aborted with textStatus "timeout". 0 means none.
cache Set false to append a _=timestamp parameter so GET requests are not served from cache.

Callbacks and what they receive

  • success(data, textStatus, jqXHR): the request worked and the body was parsed. data is already a JavaScript object when dataType is "json".
  • error(jqXHR, textStatus, errorThrown): anything went wrong. textStatus is one of "error", "timeout", "abort" or "parsererror". errorThrown is the HTTP status text, such as "Not Found", or empty for a network failure.
  • complete(jqXHR, textStatus): runs after success or error. Ideal for hiding a spinner.

The jqXHR object (jQuery's enhanced XMLHttpRequest) carries status (404), statusText, responseText and, for JSON, responseJSON.

An important point: error is not only for network failures. A server that answers 404 or 500 is a perfectly healthy connection, but jQuery treats any status outside 200-299 (and 304) as an error. Another trap is a 200 response whose body is not valid JSON when you asked for dataType: "json". That ends in error with textStatus "parsererror".

Success, 404, timeout and parse error

Read the output for each button. The 404 is an error with errorThrown set to Not Found; the broken body is a parsererror even though the status is 200; and the slow one ends as "timeout" with status 0 because no response ever arrived.

Sending data

For a GET request, data is appended to the URL as a query string. For a POST it is sent in the body. An object is converted with $.param(), so arrays and nested objects work:

JavaScript
$.ajax({ url: "/api/search", data: { q: "jquery", tags: ["js", "ui"] } });
// GET /api/search?q=jquery&tags%5B%5D=js&tags%5B%5D=ui

By default the body of a POST is form-encoded (name=Ada&role=admin), which is what traditional server frameworks expect. To send JSON instead, serialize it yourself and set the content type. Setting contentType alone is not enough, because jQuery would still try to form-encode an object.

JavaScript
$.ajax({
  url: "/api/echo",
  method: "POST",
  contentType: "application/json",
  data: JSON.stringify({ name: "Ada", role: "admin" })
});

Headers

Use headers for fixed values such as an API token:

JavaScript
$.ajax({ url: "/api/me", headers: { "X-Token": "abc123", "Accept": "application/json" } });

For anything that needs computing right before sending (a fresh CSRF token, for example), use beforeSend: function (jqXHR) { jqXHR.setRequestHeader("X-CSRF", token); }. Returning false from beforeSend cancels the request.

Form-encoded versus JSON bodies, with a header

Notice that the demo handles the result with .done(), a method on the object that $.ajax() returns, rather than a success option. That object is a promise, and it is usually the nicer style; Deferreds, Promises and Ajax Events covers it fully.

Choosing dataType

dataType tells jQuery how to convert the response before handing it to you. With "json" you receive an object, with "html" a string (and with "script" the code is executed). When you leave it out, jQuery inspects the response Content-Type, which works well when the server is correct but silently gives you a string when it is not. If you know what you expect, say so. One more reason: with an explicit dataType: "json", invalid JSON becomes a clean parsererror rather than a string that fails later in your code.

A few more settings worth knowing

  • statusCode: { 404: function () { ... } } runs a specific callback per HTTP status, in addition to the general ones.
  • context: element sets what this is inside the callbacks, which saves var self = this.
  • async: false makes the request block the whole page. It is deprecated, so never use it.
  • global: false stops the request from firing global events such as ajaxStart, which is useful for background polling.

The options reference

The settings object has more than fifty keys. You will use a handful all the time (url, method, data, dataType, headers, timeout) and the rest only occasionally. This section covers the ones people look up most, grouped by job.

Shaping what is sent

Option What it does
traditional: true serialises arrays the old way, tags=a&tags=b, instead of tags[]=a&tags[]=b (see Ajax shorthands)
xhrFields: { withCredentials: true } sets properties on the underlying XMLHttpRequest, most often to send cookies on cross-origin requests
username, password credentials for HTTP authentication; avoid them in browser code, because they end up in your script
crossDomain: true forces jQuery to treat a same-domain URL as cross-domain (adds no X-Requested-With); jQuery normally works this out from the URL
contentType the request Content-Type; use "application/json" with JSON.stringify(data) and processData: false for JSON bodies
scriptCharset the charset for script and jsonp requests that load a <script> tag

Reading what comes back

Option What it does
dataFilter: function (raw, type) cleans the raw response string before jQuery converts it, for example to strip a )]}', prefix or unwrap an envelope; you return the string to use
mimeType: "text/plain" overrides the response MIME type the browser sees, so it is read as text
ifModified: true sends If-Modified-Since / If-None-Match using values from the last response of that URL; a 304 becomes success with textStatus "notmodified"
converters adds your own type conversions, such as "text mydate": parseMyDate
jsonp, jsonpCallback rename the callback parameter, or give the callback function a fixed name; use jsonpCallback only when a server forces a specific name

Reacting to results

statusCode takes an object of functions keyed by HTTP status. Success codes receive the same arguments as success; error codes receive the same arguments as error. They run in addition to the general callbacks, which makes them the neat way to handle 401 or 404 in one place without an if in every error handler.

dataFilter, statusCode and ifModified

The first button shows dataFilter removing a protective prefix so that JSON.parse succeeds. The second shows the specific 404 callback running alongside the general error. The third returns data the first time and a 304 the second time, which jQuery reports as a successful "notmodified" with no data: your code must keep the copy it already has.

Defaults and global events

$.ajaxSetup({ timeout: 8000, headers: { "X-Requested-With": "XMLHttpRequest" } }) changes defaults for every later call, although a per-call option always wins; most teams now prefer a small wrapper function over global defaults. global: false skips ajaxStart, ajaxSend and friends for one request. For a complete list of the keys, see the official jQuery.ajax() documentation, and for how the callbacks interact with promises read Deferreds, Promises and Ajax Events.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. The server replies with status 404 and a JSON body. Which callback runs?

    jQuery treats every status outside 200-299 (and 304) as an error, even though the network request itself succeeded. complete also runs afterwards, but error is the one that fires first.
  2. 2. You request dataType: 'json' and the server returns status 200 with the text 'oops'. What is textStatus in the error callback?

    The body could not be converted to JSON, so jQuery reports a parsererror despite the 200 status.
  3. 3. How do you send a JSON body with a POST?

    dataType describes the response. For the request body you set contentType and serialize the data yourself.
  4. 4. What does timeout: 600 do?

    If no response arrives within that time, the request is aborted and the error callback runs with textStatus set to timeout.

Summary

  • $.ajax(settings) is the engine behind all of jQuery's AJAX helpers; only url is required.
  • data becomes a query string for GET and the body for POST; to send JSON, set contentType and JSON.stringify the data.
  • dataType controls how the response is parsed. Invalid JSON gives parsererror, an HTTP 4xx/5xx gives error, and a slow server gives timeout.
  • success, error and complete receive the data or the jqXHR object, which holds status, statusText and responseJSON.
  • Use headers or beforeSend for request headers. The stand-in server pattern keeps every lesson runnable without a network.

Most day-to-day requests are shorter than this. See the shortcuts in $.get, $.post, $.getJSON and .load().