jQuery AJAX: A Practical Guide to Asynchronous Requests, from Basic Examples to Error Handling

An up-to-date guide to jQuery AJAX for loading data without a full page refresh, submitting forms, handling JSON, errors, timeouts, CORS and concurrent requests.

jQuery AJAX: A Practical Guide to Asynchronous Requests, from Basic Examples to Error Handling

AJAX lets a web page communicate with a server without performing a full reload. With jQuery it remains valuable in established projects, administration panels and applications that already depend on the library. The browser sends an HTTP request, receives data—often JSON—and updates only the relevant part of the interface.

The official documentation identifies $.ajax() as the engine behind jQuery Ajax requests. Shortcuts such as $.get(), $.post(), $.getJSON() and .load() cover common cases, while $.ajax() controls methods, headers, timeouts, data formats and failures.

Load the right jQuery build

At the time of writing, the project lists jQuery 4.0.0 as the stable release. AJAX requires the full build: the slim build explicitly excludes Ajax and effects. Use the minified production file and, when loading from a CDN, prefer a tag with Subresource Integrity.

<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>

Your first $.ajax() request

$.ajax({
  url: "/api/posts",
  method: "GET",
  dataType: "json",
  timeout: 10000
})
.done(function (data) { console.log(data); })
.fail(function (jqXHR, textStatus, errorThrown) {
  console.error("Request failed:", textStatus, errorThrown);
})
.always(function () { console.log("Request finished"); });

url identifies the resource, method the HTTP verb and dataType the expected response format. A timeout is measured in milliseconds and starts when $.ajax() is called.

jqXHR and asynchronous handling

$.ajax() returns a jqXHR object implementing jQuery’s Promise interface. Use .done(), .fail(), .always() and .then(). The old .success(), .error() and .complete() methods were removed in jQuery 3.0.

const request = $.ajax({ url: "/api/search", data: { q: "ajax" } });
$("#cancel").on("click", function () { request.abort(); });

GET, POST and data serialization

When data is an object, jQuery normally serializes it into a query string through jQuery.param().

$.get("/api/search", { q: "jquery", page: 1 })
  .done(function (results) { renderResults(results); });

Traditional forms can use .serialize():

$("#contact-form").on("submit", function (event) {
  event.preventDefault();
  $.post("/api/contact", $(this).serialize())
    .done(function () { $("#message").text("Message sent"); })
    .fail(showRequestError);
});

For a JSON API, serialize the body and declare its media type:

$.ajax({
  url: "/api/users",
  method: "POST",
  contentType: "application/json; charset=UTF-8",
  dataType: "json",
  data: JSON.stringify({ name: "Ada", role: "editor" })
});

contentType describes what is sent; dataType describes what is expected back.

HTTP errors and useful feedback

A robust interface distinguishes validation, authentication, authorization and server errors. Use statusCode for specific responses and .fail() for the general case.

$.ajax({
  url: "/api/profile",
  method: "PUT",
  contentType: "application/json",
  data: JSON.stringify(profile),
  statusCode: {
    401: function () { window.location.href = "/login"; },
    422: function (jqXHR) { showValidationErrors(jqXHR.responseJSON); }
  }
}).fail(function (jqXHR, textStatus) {
  if (textStatus === "timeout") showMessage("The server did not respond in time.");
  else if (jqXHR.status >= 500) showMessage("Temporary server error.");
});

Loading states and concurrent requests

Temporarily disabling a submit button prevents duplicate writes. Global ajaxStart and ajaxStop events can control a page-wide spinner, but component-specific state is often clearer in beforeSend and .always().

const $button = $("#save");
$.ajax({
  url: "/api/settings",
  method: "POST",
  data: $("#settings").serialize(),
  beforeSend: function () { $button.prop("disabled", true); }
}).always(function () { $button.prop("disabled", false); });

For live search, abort the previous request or ignore stale responses; otherwise a slow response can overwrite newer results.

CORS, credentials and security

Cross-origin requests are governed by browser CORS rules. The server must send suitable headers; client JavaScript alone cannot fix a CORS policy. When the server permits cross-origin cookies, use xhrFields: { withCredentials: true }, together with an explicit allowed origin and credential support on the server.

AJAX does not replace server-side security. Validate input and authorization, use CSRF protection where appropriate and never inject untrusted markup through .html(). Prefer .text() for user-controlled text. JSONP executes script and is a legacy technique that should not be used with untrusted sources.

When jQuery AJAX still makes sense

For a new dependency-free project, native fetch() is often lighter. In an application already using jQuery, its Ajax API remains consistent and well integrated with forms. Do not add jQuery only for Ajax, but use it deliberately when it is already part of the stack.

Final checklist

  • Use the full build, not slim.
  • Define method, format, timeout and failure handling.
  • Distinguish contentType from dataType.
  • Use .done(), .fail() and .always().
  • Handle duplicate and out-of-order requests.
  • Enforce authentication, authorization, CSRF and validation on the server.
  • Provide loading states and understandable messages.

Share

What's Your Reaction?

Like Like 0
Dislike Dislike 0
Love Love 0
Funny Funny 0
Angry Angry 0
Sad Sad 0
Wow Wow 0