jQuery $.ajax() Method

The $.ajax() method is the most powerful and flexible AJAX method in jQuery. It gives you full control over every aspect of an HTTP request — method type, headers, data format, success handling, error handling, and more. All other jQuery AJAX shortcuts like $.get() and $.post() are built on top of $.ajax().

Basic Syntax

$.ajax({
    url: "server-endpoint",
    type: "GET",          // or "POST", "PUT", "DELETE"
    data: { },            // data to send (optional)
    dataType: "json",     // expected response format
    success: function(response) {
        // runs when request succeeds
    },
    error: function(xhr, status, error) {
        // runs when request fails
    }
});

Important $.ajax() Options

OptionPurposeDefault
urlThe server URL to send the request toCurrent page
typeHTTP method: GET, POST, PUT, DELETEGET
dataData sent to the servernone
dataTypeExpected response type: json, html, text, xmlauto-detect
successCallback when request succeedsnone
errorCallback when request failsnone
completeCallback when request finishes (success or error)none
asynctrue = asynchronous, false = synchronoustrue
timeoutMilliseconds before request times out0 (no limit)
contentTypeContent type of data sent to serverapplication/x-www-form-urlencoded
headersExtra HTTP headers to sendnone
beforeSendCallback that runs before the request startsnone

Diagram: $.ajax() Request Lifecycle

  $.ajax() called
       │
  beforeSend() runs  → show loading spinner
       │
  HTTP request sent to server
       │
       ├── Server responds OK  → success() runs  → hide spinner
       │
       └── Server responds ERROR → error() runs  → show error msg
       │
  complete() runs ALWAYS (after success or error)

GET Request — Fetch JSON Data

$(document).ready(function() {
    $.ajax({
        url: "https://api.example.com/users",
        type: "GET",
        dataType: "json",
        success: function(data) {
            $.each(data, function(i, user) {
                $("#userList").append("<li>" + user.name + " — " + user.email + "</li>");
            });
        },
        error: function(xhr, status, error) {
            $("#errorMsg").text("Failed to load users: " + error);
        }
    });
});

POST Request — Send Form Data

$(document).ready(function() {
    $("#loginForm").submit(function(e) {
        e.preventDefault();

        $.ajax({
            url: "login.php",
            type: "POST",
            data: {
                username: $("#username").val(),
                password: $("#password").val()
            },
            dataType: "json",
            success: function(response) {
                if (response.status === "ok") {
                    window.location.href = "dashboard.html";
                } else {
                    $("#loginError").text(response.message);
                }
            },
            error: function() {
                $("#loginError").text("Server error. Please try again.");
            }
        });
    });
});

Using beforeSend and complete for Loading State

$.ajax({
    url: "data.json",
    type: "GET",
    beforeSend: function() {
        $("#loader").show();
        $("#content").hide();
    },
    success: function(data) {
        $("#content").html(data.html).show();
    },
    error: function() {
        $("#errorBox").text("Could not load data.").show();
    },
    complete: function() {
        $("#loader").hide();   // always hides the loader
    }
});

Diagram: Loading Spinner Pattern

  User clicks button
       │
  beforeSend → spinner appears, content hides
       │
  Request in progress...
       │
  success  → content updates and shows
  complete → spinner hides

  (If error: error msg shows, spinner still hides via complete)

Setting a Request Timeout

$.ajax({
    url: "slow-api.php",
    type: "GET",
    timeout: 5000,     // 5 seconds max wait
    success: function(data) {
        console.log(data);
    },
    error: function(xhr, status) {
        if (status === "timeout") {
            alert("Request timed out. Please try again.");
        }
    }
});

Sending JSON in a POST Request

$.ajax({
    url: "api/save",
    type: "POST",
    contentType: "application/json",
    data: JSON.stringify({
        name: "Ravi",
        age: 28,
        city: "Delhi"
    }),
    dataType: "json",
    success: function(response) {
        console.log("Saved:", response.id);
    }
});

Promise-Style with .done() .fail() .always()

Since jQuery 1.8, $.ajax() returns a Deferred object. You can attach callbacks using promise-style chaining instead of options.

$.ajax({ url: "data.json", type: "GET" })
    .done(function(data) {
        console.log("Success:", data);
    })
    .fail(function(xhr, status, error) {
        console.log("Error:", error);
    })
    .always(function() {
        $("#loader").hide();
    });

Quick Summary

  • $.ajax() is the full-featured jQuery AJAX method with all options.
  • Key options: url, type, data, dataType, success, error, complete.
  • Use beforeSend and complete to show and hide loading indicators.
  • Set a timeout to handle slow server responses gracefully.
  • Use promise chaining (.done(), .fail(), .always()) for cleaner code structure.

Leave a Comment

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