$.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
Fundamentals
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.
Concept
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 document — ajaxStart, 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.
Foundation
📝 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.
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.
$.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.
Hands-On
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.
User clicks #load → $.ajax GET runs
Server returns JSON → .done() fires → #result shows "Title: ..."
Network or server error → .fail() runs instead
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.
User enters title and clicks #save
jQuery serializes data object → POST body
Server responds 201 → .done() shows "Created post id: 101" (demo API)
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().
Valid user id → .done() fills #name and #email
404 or network error → .fail() shows error message
Either outcome → .always() hides #spinner
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.
Click #fetch-comments → GET /posts/1/comments
.done() receives parsed JSON array → builds <li> list in #list
cache: false adds _=timestamp to avoid stale GET cache
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.
Click #load-main → #overlay appears (ajaxStart) then hides (ajaxStop)
Click #prefetch → request completes but overlay never shows
.done() on the prefetch still runs — only global events are skipped
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.
Applications
🚀 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 sync — global: 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.
Important
📝 Notes
$.ajax() is asynchronous — code after the call runs before the response arrives.
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.
Compatibility
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 ChromeAll versions · Desktop & Mobile
Full support
Mozilla FirefoxAll versions · Desktop & Mobile
Full support
Apple SafariAll versions · macOS & iOS
Full support
Microsoft EdgeAll versions · Chromium & Legacy
Full support
Internet ExplorerIE 6+ · Legacy environments
Full support
OperaAll 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.
Wrap Up
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.
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
Summary
Key Takeaways
Knowledge Unlocked
Six things to remember about $.ajax()
Settings in, jqXHR out, callbacks chain.
6
Core concepts
api01
Core API
$.ajax(settings)
Foundation
xhr02
jqXHR
Return value
Deferred
done03
done/fail
Chain callbacks
Promises
json04
dataType
Parse response
json
post05
POST data
method + data
Write
off06
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.