jQuery ajax() Method

Beginner
⏱️ 14 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Core Ajax API

What You’ll Learn

$.ajax() is jQuery’s full-featured HTTP client. This tutorial covers the settings object, the jqXHR object it returns, chaining .done(), .fail(), and .always(), sending GET and POST data, parsing JSON with dataType, opting out of global events with global: false, and when to reach for shorthands like $.get() instead.

01

Core API

$.ajax(settings)

02

jqXHR

Return value

03

GET/POST

method + data

04

dataType

json, html, text

05

done/fail

Promise-style

06

global:false

Skip events

Introduction

Every jQuery Ajax call — whether you write $.ajax(), $.get(), $.post(), or .load() — ultimately goes through jQuery.ajax(). It is the configurable foundation: you pass a settings object describing the URL, HTTP method, payload, expected response type, and what to do when the server answers.

Unlike one-line shorthands, $.ajax() exposes the full surface area of jQuery’s Ajax transport. You get beforeSend for last-minute header tweaks, dataType to tell jQuery how to parse the body, and global: false to keep a request invisible to document-level Ajax event listeners. The method returns a jqXHR object — chain .done(), .fail(), and .always() for clean, composable callbacks.

Understanding jQuery.ajax()

jQuery.ajax() sends an asynchronous HTTP request and returns immediately with a jqXHR object. That object wraps the underlying XMLHttpRequest (or transport jQuery selects) and implements jQuery’s Deferred/Promise interface, so you can attach success and error handlers after the call returns.

Configure the request through a plain JavaScript settings object. Common keys include url, method (alias type), data, dataType, beforeSend, cache, and global. When global is true (the default), jQuery fires global Ajax events on documentajaxStart, ajaxSend, ajaxSuccess, and the rest — which power site-wide loading spinners and analytics hooks.

💡
Beginner Tip

Start with $.get() for simple reads, but learn $.ajax() early — it is the one method you need when requirements grow. Return the jqXHR from a function so callers can chain .done() or call .abort() if the user navigates away mid-request.

📝 Syntax

The official jQuery API accepts two signatures:

1. Settings object — jQuery.ajax( settings )

jQuery
jQuery.ajax( settings )

Pass a single object with at least url. All other options are optional.

2. URL + settings — jQuery.ajax( url [, settings ] )

jQuery
jQuery.ajax( url [, settings ] )

Shorthand when the URL is the most important detail — settings merge on top.

Key settings options

  • url — string; the endpoint to request (required unless set globally via $.ajaxSetup()).
  • method (or type) — HTTP verb: "GET", "POST", "PUT", "DELETE", etc. Default is "GET".
  • data — plain object, string, or array sent with the request. For GET, appended as query string; for POST, sent in the body (default application/x-www-form-urlencoded).
  • dataType — expected response type: "json", "html", "text", "xml", or "script". jQuery parses the body accordingly before callbacks run.
  • beforeSend — function(jqXHR, settings) invoked after the request is created but before it is sent — set headers or cancel with return false.
  • global — boolean; when false, the request does not trigger global Ajax events on document. Default is true.
  • cache — boolean; when false, jQuery appends a cache-busting query parameter on GET requests. Default is true for GET, false for script/dataType script.

3. Official demo — .done() / .fail() / .always()

jQuery
$.ajax( {
  url: "https://jsonplaceholder.typicode.com/posts/1",
  dataType: "json"
} )
  .done( function( data ) {
    console.log( "Success:", data.title );
  } )
  .fail( function( jqXHR, textStatus, errorThrown ) {
    console.log( "Error:", textStatus, errorThrown );
  } )
  .always( function() {
    console.log( "Finished — success or failure" );
  } );

Return value

  • $.ajax() returns a jqXHR object — a superset of XMLHttpRequest with Deferred methods.
  • Chain .done(fn), .fail(fn), .always(fn), .then(fn) on the returned jqXHR.
  • Call jqXHR.abort() to cancel an in-flight request.
  • Read jqXHR.status, jqXHR.responseText, and jqXHR.getAllResponseHeaders() like a native XHR.

⚡ Quick Reference

GoalCode
Basic GET request$.ajax({ url: "/api/items" })
POST with form data$.ajax({ url: "/save", method: "POST", data: { name: "Ada" } })
Expect JSON response$.ajax({ url: "/api", dataType: "json" })
Success callback$.ajax(...).done(function(data) { ... })
Error callback$.ajax(...).fail(function(xhr, status, err) { ... })
Always runs$.ajax(...).always(function() { ... })
URL + settings shorthand$.ajax("/api", { method: "POST", data: payload })
Skip global Ajax events$.ajax({ url: "/x", global: false })
Cancel requestvar req = $.ajax(...); req.abort();

📋 $.ajax() vs $.get() / $.post() vs fetch

Four ways to load data — choose full control, readable shorthands, or native browser APIs.

$.ajax()
full control

Every setting exposed — headers, beforeSend, dataType, global:false, and jqXHR chaining

$.get()
GET shorthand

$.get(url, data, success) — readable one-liner; internally calls $.ajax()

$.post()
POST shorthand

$.post(url, data, success) — same idea for POST; less config than full $.ajax()

fetch()
native API

Browser built-in — no jQuery dependency; does not trigger jQuery global Ajax events

Use $.ajax() when you need fine-grained control or must participate in jQuery’s global Ajax event system. Use $.get() / $.post() for quick reads and writes. Use fetch() in modern vanilla JS projects where jQuery is not loaded.

Examples Gallery

Five progressive examples from a basic GET with .done() through JSON parsing, the two-argument signature, and global: false. Each links to a Try-it lab where you can edit and run the code in the browser.

📚 Core Patterns

GET and POST requests with promise-style callbacks on the returned jqXHR.

Example 1 — Basic GET with .done()

Fetch a JSON post from a public API and log the title when the request succeeds.

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

How It Works

$.ajax() returns a jqXHR immediately. The click handler does not block — jQuery sends the request asynchronously and invokes .done() when the server responds with a success status. Setting dataType: "json" tells jQuery to parse the body before passing it to the callback.

Example 2 — POST with data

Submit a new post title to a REST endpoint using POST and a plain object payload.

jQuery
$( "#save" ).on( "click", function() {
  var title = $( "#title" ).val();

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

How It Works

With method: "POST", jQuery sends the data object in the request body using the default application/x-www-form-urlencoded encoding. For JSON APIs that expect application/json, set contentType: "application/json" and pass data: JSON.stringify(payload).

Example 3 — dataType: "json" with .done() / .fail() / .always()

Load a user profile, handle parse errors and HTTP failures separately, and run cleanup in .always().

jQuery
function loadUser( userId ) {
  return $.ajax( {
    url: "https://jsonplaceholder.typicode.com/users/" + userId,
    dataType: "json"
  } )
    .done( function( user ) {
      $( "#name" ).text( user.name );
      $( "#email" ).text( user.email );
    } )
    .fail( function( jqXHR, textStatus ) {
      $( "#name" ).text( "Could not load user (" + textStatus + ")" );
    } )
    .always( function() {
      $( "#spinner" ).hide();
    } );
}

loadUser( 1 );
Try It Yourself

How It Works

Returning the jqXHR from loadUser() lets callers chain further handlers. .always() is the right place for UI cleanup that must run regardless of outcome — hiding spinners, re-enabling buttons, or resetting state.

📈 Signatures & Global Events

Two-argument form and opting out of document-level Ajax events.

Example 4 — Two-Argument $.ajax(url, settings)

When the URL is fixed, pass it as the first argument and keep settings separate for readability.

jQuery
var apiBase = "https://jsonplaceholder.typicode.com";

$( "#fetch-comments" ).on( "click", function() {
  $.ajax( apiBase + "/posts/1/comments", {
    dataType: "json",
    cache: false
  } )
    .done( function( comments ) {
      var html = comments.map( function( c ) {
        return "<li>" + c.email + ": " + c.body + "</li>";
      } ).join( "" );
      $( "#list" ).html( html );
    } );
} );
Try It Yourself

How It Works

Both signatures are equivalent — jQuery merges the URL into settings internally. The two-argument form reads naturally when the endpoint changes per call but options stay the same. cache: false is useful during development when browsers aggressively cache GET responses.

Example 5 — global: false — Silent Background Request

A prefetch request that completes without firing global ajaxStart / ajaxStop loading indicators.

jQuery
$( document ).on( "ajaxStart", function() {
  $( "#overlay" ).show();
} ).on( "ajaxStop", function() {
  $( "#overlay" ).hide();
} );

// Visible request — triggers global events
$( "#load-main" ).on( "click", function() {
  $.ajax( { url: "https://jsonplaceholder.typicode.com/posts/1" } );
} );

// Silent prefetch — no overlay
$( "#prefetch" ).on( "click", function() {
  $.ajax( {
    url: "https://jsonplaceholder.typicode.com/posts/2",
    global: false
  } ).done( function( data ) {
    console.log( "Prefetched:", data.id );
  } );
} );
Try It Yourself

How It Works

global: false opts a single request out of all document-level Ajax events. Per-request .done() / .fail() / .always() callbacks are unaffected. Use this for analytics beacons, silent prefetch, or third-party widgets that should not flash your page-wide loading UI.

🚀 Common Use Cases

  • REST API calls — CRUD operations against JSON backends with dataType: "json" and method-specific verbs.
  • Form submission — POST serialized form fields without a full page reload; update a message area in .done().
  • Partial page updates — fetch HTML fragments with dataType: "html" and inject into a container with .html().
  • Autocomplete / search — debounced GET requests; abort the previous jqXHR when the user types the next character.
  • File uploads — combine with FormData, processData: false, and contentType: false for multipart uploads.
  • Silent background syncglobal: false prefetch so global loading indicators stay hidden.

🧠 jQuery.ajax() Callback & Event Order

1

beforeSend

Settings callback runs — set headers, show a local spinner, or return false to cancel.

beforeSend
2

Global ajaxSend

If global: true, document listeners fire just before the transport sends bytes.

ajaxSend
3

success or error

Legacy settings callbacks — success on 2xx, error on failure or parse error.

success | error
4

done or fail

jqXHR Deferred callbacks — mirror success/error but chainable with other promises.

.done() | .fail()
5

always + complete

.always() and the complete setting run for both outcomes — ideal for cleanup.

.always() | complete
6

Global ajaxSuccess / ajaxError / ajaxComplete

Document-level outcome events fire, then ajaxStop when no global requests remain.

📝 Notes

  • $.ajax() is asynchronous — code after the call runs before the response arrives.
  • Prefer .done() / .fail() / .always() over legacy success / error / complete settings properties.
  • The return value is a jqXHR — store it to call .abort() or chain additional handlers.
  • dataType: "json" parses the body; invalid JSON triggers .fail() even on HTTP 200.
  • method is the modern name; type is an alias kept for backward compatibility.
  • global: false skips document Ajax events but not per-request jqXHR callbacks.
  • $.get(), $.post(), and .load() are thin wrappers around $.ajax().
  • Set defaults for all requests with $.ajaxSetup({ ... }) — override per call in the settings object.

Browser Support

jQuery.ajax() is part of jQuery’s core Ajax module — not a native DOM API. It works wherever jQuery’s Ajax transport runs: all browsers supported by your jQuery version, including legacy IE with supported jQuery builds.

jQuery 1.5+

jQuery.ajax() method

Supported in jQuery 1.x, 2.x, and 3.x across all modern browsers and IE with supported jQuery builds. jqXHR promise methods (.done, .fail, .always) arrived in jQuery 1.5. Cross-domain requests require CORS on the server or JSONP for legacy patterns.

100% With jQuery
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 in any jQuery project. Use $.ajax() for full control; $.get()/$.post() for shorthands. fetch() is the native alternative when jQuery is not loaded — it does not trigger jQuery global Ajax events.

Conclusion

jQuery.ajax() is the configurable heart of jQuery’s HTTP layer. Pass a settings object (or URL plus settings), chain .done(), .fail(), and .always() on the returned jqXHR, and use dataType to control parsing. Reach for $.get() when a one-liner suffices; reach for $.ajax() when you need headers, beforeSend, or global: false.

Every qualifying $.ajax() call can trigger global Ajax events on document. Continue with the ajaxPrefilter() tutorial to modify options globally before requests are sent, then explore ajaxStart for page-wide loading indicators.

💡 Best Practices

✅ Do

  • Chain .done() / .fail() / .always() on the returned jqXHR
  • Set dataType: "json" explicitly when you expect JSON from the server
  • Return jqXHR from helper functions so callers can chain or abort
  • Use global: false for silent background or third-party requests
  • Handle errors in .fail() — show user-friendly messages, log details server-side

❌ Don’t

  • Assume synchronous behavior — Ajax is non-blocking by default
  • Mix heavy logic in both success and .done() for the same request
  • Send sensitive data over HTTP — use HTTPS in production
  • Forget CORS — cross-origin $.ajax() calls fail without server headers
  • Leave in-flight requests running after SPA navigation — call .abort() on teardown

Key Takeaways

Knowledge Unlocked

Six things to remember about $.ajax()

Settings in, jqXHR out, callbacks chain.

6
Core concepts
xhr 02

jqXHR

Return value

Deferred
done 03

done/fail

Chain callbacks

Promises
json 04

dataType

Parse response

json
post 05

POST data

method + data

Write
off 06

global:false

Skip events

Private

❓ Frequently Asked Questions

jQuery.ajax() is the core jQuery method for making HTTP requests. Pass a settings object (or a URL plus settings) to configure the request — url, method, data, dataType, callbacks, and more. It returns a jqXHR object you can chain with .done(), .fail(), and .always(). Shorthands like $.get() and $.post() are built on top of $.ajax().
It returns a jqXHR object — a superset of the XMLHttpRequest object that also implements the Promise interface. Chain .done(fn) for success, .fail(fn) for errors, and .always(fn) for either outcome. You can also call jqXHR.abort() to cancel an in-flight request.
Both run when a request succeeds. 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. success, error, and complete still work but are legacy-style per-request callbacks.
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 for it. Per-request done(), fail(), and always() callbacks still run. Use global: false for silent background requests or third-party widgets that should not trigger page-wide loading indicators.
Use $.get(url, data, success) for simple GET requests with minimal configuration — it is a readable shorthand. Use $.ajax() when you need full control: custom headers, beforeSend, POST with JSON, dataType, global: false, or multiple chained callbacks. $.get() and $.post() internally call $.ajax() with preset options.
When you set dataType: "json", jQuery expects JSON from the server and parses the response body into a JavaScript object before passing it to success or .done(). If parsing fails, the request is treated as an error and .fail() runs. Omit dataType to let jQuery infer from the Content-Type header, or set "html", "text", "xml", or "script" for other response types.
Did you know?

Since jQuery 1.5, the object returned by $.ajax() is a jqXHR that implements the Promise interface — .done(), .fail(), and .always() were added alongside jQuery Deferred. The older success, error, and complete settings still work, but chaining jqXHR methods composes cleanly with other Deferreds. Shorthands $.get() and $.post() are implemented as thin wrappers that call jQuery.ajax() with preset options.

Next: ajaxPrefilter() Method

Register global hooks that modify Ajax settings before each request — custom defaults, abort-on-retry, and dataType filters.

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.

6 people found this page helpful