jQuery AJAX Advanced

While $.get() and $.post() cover most common use cases, jQuery's $.ajax() method provides complete control over every aspect of an AJAX request — custom headers, timeout handling, error callbacks, and more.

$.ajax() Method

The $.ajax() method is the foundation that all other jQuery AJAX methods are built upon. It takes a single configuration object.

Basic Syntax

$.ajax({
  url: "endpoint.php",
  type: "GET",
  data: { id: 42 },
  dataType: "json",
  success: function(response) {
    console.log(response);
  },
  error: function(xhr, status, errorMsg) {
    console.log("Error: " + errorMsg);
  }
});

AJAX Settings (Options)

  • url — The server URL for the request
  • type — HTTP method: "GET", "POST", "PUT", "DELETE"
  • data — Data to send with the request
  • dataType — Expected response format: "json", "html", "text"
  • contentType — MIME type of data being sent
  • timeout — Maximum wait time in milliseconds
  • headers — Custom HTTP headers
  • cache — Whether the browser should cache the result

Example with Timeout and Custom Header

$.ajax({
  url: "api/products",
  type: "GET",
  dataType: "json",
  timeout: 5000,
  headers: { "Authorization": "Bearer mytoken123" },
  success: function(data) {
    $.each(data, function(i, product) {
      $("#productList").append("<li>" + product.name + "</li>");
    });
  },
  error: function(xhr, status) {
    if (status === "timeout") {
      alert("The request timed out. Please try again.");
    }
  }
});

Handling Errors

The error callback receives three arguments:

  • xhr — The XMLHttpRequest object
  • status — Error type: "timeout", "error", "abort", "parsererror"
  • errorThrown — The HTTP error message (e.g., "Not Found")
$.ajax({
  url: "data.json",
  type: "GET",
  dataType: "json",
  success: function(data) {
    $("#result").html("Data loaded successfully.");
  },
  error: function(xhr, status, errorThrown) {
    console.log("Status Code: " + xhr.status);
    console.log("Error Type: " + status);
    $("#result").html("Something went wrong. Please try again.");
  }
});

AJAX Global Events

jQuery provides global event handlers that fire for every AJAX request on the page — useful for showing and hiding a loading indicator.

$(document).ajaxStart(function() {
  $("#spinner").show();    // Show before any AJAX request starts
});

$(document).ajaxStop(function() {
  $("#spinner").hide();    // Hide after all requests complete
});

Working with JSON Data

$.getJSON() is a shorthand for $.ajax() with dataType: "json".

$.getJSON("users.json", function(data) {
  $.each(data, function(index, user) {
    $("#userList").append("<li>" + user.name + " — " + user.role + "</li>");
  });
});

Sample JSON (users.json)

[
  { "name": "Alice", "role": "Admin" },
  { "name": "Bob",   "role": "Editor" },
  { "name": "Carol", "role": "Viewer" }
]

Sending JSON Data to the Server

When sending data to a REST API, set contentType to "application/json" and use JSON.stringify().

var newUser = { name: "Dave", email: "dave@example.com" };

$.ajax({
  url: "api/users",
  type: "POST",
  contentType: "application/json",
  data: JSON.stringify(newUser),
  dataType: "json",
  success: function(response) {
    alert("User created with ID: " + response.id);
  }
});

$.ajaxSetup() — Setting Defaults

Sets global defaults for all AJAX calls to avoid repeating common settings.

$.ajaxSetup({
  dataType: "json",
  headers: { "X-API-Key": "mykey" }
});

// These calls now use the defaults automatically
$.ajax({ type: "GET", url: "products" });
$.ajax({ type: "POST", url: "orders", data: orderData });

Key Points

  • $.ajax() is the most configurable jQuery AJAX method.
  • Always include an error callback to handle failures gracefully.
  • Global AJAX events (ajaxStart, ajaxStop) are ideal for loading indicators.
  • Use JSON.stringify() and contentType: "application/json" when sending JSON in a POST body.
  • $.ajaxSetup() avoids repeating common settings across multiple AJAX calls.
  • Always validate and sanitize data on the server — never trust client-side data alone.

Leave a Comment

Your email address will not be published. Required fields are marked *