jQuery AJAX

AJAX with jQuery: The $.ajax() Method

Use jQuery $.ajax() to configure HTTP requests, data types, callbacks, and error handling.

AJAX with jQuery: The $.ajax() Method

The $.ajax() method provides detailed control over an HTTP request in applications that already use jQuery. It returns a jqXHR object that supports promise-style methods.

A JSON request

$.ajax({
  url: '/api/status.php',
  method: 'GET',
  dataType: 'json'
})
.done(function (data) {
  $('#status').text(data.message);
})
.fail(function (xhr) {
  console.error('Request failed:', xhr.status);
});

Important options

url identifies the endpoint, method selects the HTTP method, data supplies request data, dataType describes the expected response, and contentType describes the request body format. These settings are not interchangeable.

Error handling

Use .fail() to handle HTTP and network errors. Inspect the response status and parse only documented response formats. Never insert untrusted response text with .html(); use .text() for plain text or sanitize and validate HTML with a trusted approach.

For new projects without a jQuery dependency, the native Fetch API is generally simpler.

Share this page Help other developers discover this resource.