jQuery .ajax() Method

Beginner
9 min read
Updated: Oct 2026
5 examples
Live preview

What Is $.ajax()?

jQuery.ajax() is the core Ajax method (since 1.0; URL+settings form since 1.5). Pass a settings object to send an HTTP request. It returns a jqXHR — chain .done(), .fail(), and .always(). $.get(), $.post(), and .load() are built on top of it.

Remember
$.ajax({
  url: "/api/items",
  method: "GET",       // or type: "GET"
  dataType: "json"
}).done(function (data) {
  // success
}).fail(function () {
  // error
}).always(function () {
  // finished either way
});

// Also valid: $.ajax(url, settings)
NeedUse
Full control$.ajax(settings)
Simple GET$.get()
Simple POST$.post()
Default options$.ajaxSetup()
Global “about to send”ajaxSend

How to Use $.ajax()

Configure the request, send it, then handle the result on the returned jqXHR.

  1. Call $.ajax({ url, method, data, dataType, … }) (or $.ajax(url, settings)).
  2. Chain .done() for success and .fail() for errors.
  3. Use .always() for cleanup that must run either way.
  4. Set global: false when the request should skip document Ajax events.
  5. Call jqXHR.abort() if you need to cancel an in-flight request.
PieceRequired?Role
urlYes*Endpoint (*or set via $.ajaxSetup())
method / typeNoHTTP verb — default "GET"
dataNoQuery string (GET) or body (POST)
dataTypeNoHow to parse the response (json, html, …)
beforeSendNoLast chance to set headers or return false to cancel
globalNoDefault true — set false to skip global events

Pseudocode

Pseudocode
call $.ajax(settings)  →  returns jqXHR immediately

if beforeSend returns false:
    cancel — do not send

if settings.global !== false:
    fire ajaxStart (first active) then ajaxSend

send HTTP request asynchronously

when response arrives:
    if success:
        parse body using dataType
        fire ajaxSuccess (if global)
        run .done() handlers
    else:
        fire ajaxError (if global)
        run .fail() handlers

    fire ajaxComplete (if global)
    run .always() handlers
    fire ajaxStop when no global requests remain

Cheat Sheet

Keep these patterns handy while wiring Ajax calls.

TopicDetail
Signatures$.ajax(settings) · $.ajax(url, settings)
ReturnsjqXHR (XHR + Deferred)
Success.done(fn) or settings success
Error.fail(fn) or settings error
Always.always(fn) or settings complete
CanceljqXHR.abort() or beforeSend → false
JSONdataType: "json"
Silentglobal: false

Live Preview

Run a real $.ajax() call and watch .done() / .fail() update the log.

Live demo uses a public JSON API. Needs network access.

Result
Ready — pick an action and click Run.

jQuery Examples

Short, copy-ready snippets. Open DevTools Console, or use Try It Yourself for a live editor.

Example 1 — Basic GET with .done()

Fetch JSON and read a field when the request succeeds.

jQuery
$("#load").on("click", function () {
  $.ajax({
    url: "https://jsonplaceholder.typicode.com/posts/1",
    method: "GET"
  }).done(function (data) {
    $(".log").text("Title: " + data.title);
  }).fail(function () {
    $(".log").text("Request failed.");
  });
});
Try It Yourself

How It Works

  1. Click. The handler calls $.ajax() with a URL and method.
  2. Send. jQuery starts an async GET and returns a jqXHR.
  3. Success. .done() receives the parsed response body.
  4. Error. .fail() runs if the network or HTTP status fails.

Example 2 — POST with data

Send form-style fields in the request body and read the created resource.

jQuery
$("#post").on("click", function () {
  $.ajax({
    url: "https://jsonplaceholder.typicode.com/posts",
    method: "POST",
    data: { title: "Hello Ajax", body: "Posted with $.ajax()", userId: 1 }
  }).done(function (data) {
    $(".log").text("Created id: " + data.id + " — " + data.title);
  });
});
Try It Yourself

How It Works

  1. Method. method: "POST" puts data in the body (not the query string).
  2. Encode. By default jQuery sends application/x-www-form-urlencoded.
  3. Response. The demo API returns JSON with an id.
  4. Update. .done() shows the new id and title.

Example 3 — dataType + done / fail / always

Parse JSON automatically and chain all three promise-style handlers.

jQuery
$.ajax({
  url: "https://jsonplaceholder.typicode.com/posts/1",
  dataType: "json"
})
  .done(function (data) {
    $(".log").append("\ndone: userId=" + data.userId);
  })
  .fail(function () {
    $(".log").append("\nfail");
  })
  .always(function () {
    $(".log").append("\nalways (finished)");
  });
Try It Yourself

How It Works

  1. Parse. dataType: "json" turns the body into an object before .done().
  2. Success path. .done() runs only when the request succeeds.
  3. Error path. .fail() runs on HTTP or parse errors.
  4. Cleanup. .always() runs after either outcome.

Example 4 — $.ajax(url, settings)

Pass the URL first when it is the main detail — settings merge on top.

jQuery
$("#go").on("click", function () {
  $.ajax("https://jsonplaceholder.typicode.com/users/1", {
    method: "GET",
    dataType: "json"
  }).done(function (user) {
    $(".log").text(user.name + " — " + user.email);
  });
});
Try It Yourself

How It Works

  1. Two args. First argument is the URL; second is optional settings.
  2. Merge. Settings apply on top of defaults (and $.ajaxSetup()).
  3. Same return. You still get a jqXHR for chaining.
  4. When. Handy when the URL is the primary variable in a helper.

Example 5 — Opt Out with global: false

Private requests skip document Ajax events but still run their own callbacks.

jQuery
$(document).on("ajaxStart", function () {
  $(".log").append(" ajaxStart");
});

// Fires ajaxStart
$.ajax({ url: "/api/public" });

// Does NOT fire ajaxStart
$.ajax({ url: "/api/silent", global: false });
Try It Yourself

How It Works

  1. Default. Ajax calls participate in global events on document.
  2. Opt out. global: false skips ajaxStart, ajaxSend, and the rest.
  3. Local still works. Per-request .done() / .fail() still run.
  4. When. Use for silent polling or third-party widgets.

Edge Cases & Pitfalls

Check these before shipping Ajax-heavy pages.

async

Avoid async: false

Synchronous Ajax freezes the UI. Using it with Deferred methods is deprecated since 1.8.

parse

Invalid JSON → .fail()

With dataType: "json", a parse error is treated as a failed request — not a successful empty object.

cancel

Cancel with beforeSend or .abort()

Return false from beforeSend to stop before send, or call jqXHR.abort() after.

global

global: false stays silent

Those requests never trigger document Ajax events. Per-request callbacks still work.

Browser Support

jQuery.ajax() has been part of jQuery since 1.0. The $.ajax(url, settings) form and jqXHR Deferred methods (.done() / .fail() / .always()) date from 1.5. Prefer a current jQuery 3.x build.

✓ Stable · jQuery 1.0+

jQuery.ajax()

Works in every browser that runs your loaded jQuery version. Uses XMLHttpRequest under the hood (or a custom transport). Native fetch() is separate and does not trigger jQuery global Ajax events.

100% jQuery Ajax API
Google Chrome All versions · Desktop & Mobile
Full support
Mozilla Firefox All versions · Desktop & Mobile
Full support
Apple Safari All versions · macOS & iOS
Full support
Microsoft Edge All versions · Chromium & Legacy
Full support
Internet Explorer IE 6+ · Legacy environments
Full support
Opera All modern versions
Full support
$.ajax() Universal

Bottom line: Safe for everyday apps. Prefer .done()/.fail()/.always(), keep requests async, and use global: false for silent background calls.

Performance Notes

ApproachCostBest for
Async $.ajax() (default)CheapAlmost all UI work
Shorthands $.get() / $.post()SameSimple reads/writes
async: falseExpensive / riskyAvoid — freezes the UI

Keep requests asynchronous, abort obsolete ones when the user navigates away, and avoid heavy DOM work inside every global Ajax handler.

Key Takeaways

  • Role: core Ajax API — shorthands like $.get() call it under the hood.
  • Return: jqXHR — chain .done(), .fail(), .always().
  • Settings: url, method, data, dataType, global, beforeSend.
  • Stay async: avoid async: false; cancel with .abort() when needed.

One line: $.ajax() is jQuery’s full-featured HTTP client — configure settings, then chain the jqXHR.

Frequently Asked Questions

jQuery.ajax() is the core jQuery method for HTTP requests. Pass a settings object (or a URL plus settings) to configure url, method, data, dataType, and more. It returns a jqXHR you can chain with .done(), .fail(), and .always(). Shorthands like $.get() and $.post() call $.ajax() internally.
A jqXHR object — a superset of XMLHttpRequest that also implements the Promise/Deferred interface. Chain .done(fn) for success, .fail(fn) for errors, and .always(fn) for either outcome. Call jqXHR.abort() to cancel an in-flight request.
Both run on success. success is a settings property: $.ajax({ success: fn }). done() is chained on the returned jqXHR: $.ajax(...).done(fn). Prefer done/fail/always — they compose with other Deferreds and match modern promise style.
When global is false, the request opts out of all global Ajax events on document — ajaxStart, ajaxSend, ajaxSuccess, ajaxError, ajaxComplete, and ajaxStop will not fire. Per-request done(), fail(), and always() still run.
Use $.get(url, data, success) for simple GET requests with minimal configuration. Use $.ajax() when you need full control: custom headers, beforeSend, POST with structured data, dataType, global: false, or multiple chained callbacks.
When dataType is "json", jQuery expects JSON and parses the body into a JavaScript value before .done() runs. If parsing fails, the request is treated as an error and .fail() runs. Other common values: "html", "text", "xml", "script".

Next: ajaxPrefilter

Inspect or rewrite Ajax options before a request is sent.

ajaxPrefilter tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

10 people found this page helpful