AJAX
|
This section documents jQuery 3.x (the current major line — no specific patch version is pinned). This content was generated with the assistance of AI and should be verified against the official jQuery API reference before being relied on in production, since API details and deprecations continue to change between releases. jQuery is legacy-leaning: modern browsers implement native equivalents for almost everything it does
( This section’s bibliography lists the reference material consulted while preparing these pages. |
"AJAX" (Asynchronous JavaScript and XML) means updating a page with server data without a full reload. jQuery
wraps XMLHttpRequest in jQuery.ajax() plus a set of shorthands, and — since jQuery 3 — returns a
Promises/A+ compliant object.
jQuery.ajax(url, settings)
jQuery.ajax('/api/users', {
method: 'POST', // HTTP verb (alias: type); default 'GET'
data: { name: 'Ada' }, // GET -> query string; POST -> request body
dataType: 'json', // how to parse the response: 'json' | 'text' | 'html' | 'script'
contentType: 'application/json; charset=UTF-8', // request body media type
headers: { 'X-Requested-With': 'XMLHttpRequest' },
timeout: 8000, // ms before the request is aborted with a 'timeout' error
beforeSend: (jqXHR, settings) => { /* e.g. show a spinner, set an auth header */ }
});
Shorthands
jQuery.get('/api/users', params); // GET
jQuery.post('/api/users', body); // POST
jQuery.getJSON('/api/users', params); // GET with dataType 'json'
jQuery.getScript('/widgets/chart.js'); // GET a script and execute it
$('#panel').load('/fragments/list.html'); // GET HTML and inject it into #panel
$('#panel').load('/fragments/list.html #rows'); // inject only the #rows subtree
Handling the response: the jqXHR object
Every AJAX call returns a jqXHR — a superset of the native XMLHttpRequest that is also a thenable.
Prefer the deferred-style callbacks:
jQuery.getJSON('/api/users')
.done((data, textStatus, jqXHR) => { /* 2xx: use data */ })
.fail((jqXHR, textStatus, errorThrown) => { /* network error, 4xx/5xx, parse error, timeout */ })
.always((/* ... */) => { /* runs on success OR failure -- hide the spinner here */ });
// Promises/A+ since jQuery 3 -- chainable and await-able:
try {
const data = await jQuery.getJSON('/api/users');
} catch (jqXHR) { /* ... */ }
The legacy success / error / complete settings still work but are discouraged: the deferred style
composes, supports multiple callbacks, and can be `await`ed.
// coordinating several requests
jQuery.when(jQuery.getJSON('/a'), jQuery.getJSON('/b'))
.done((aResult, bResult) => { /* both resolved; each is [data, status, jqXHR] */ });
// your own deferred (rarely needed now -- prefer a native Promise)
const d = jQuery.Deferred();
setTimeout(() => d.resolve('ok'), 100);
d.promise().then(v => console.log(v));
Serializing form data
$('#form').serialize(); // "name=Ada&role=admin" (application/x-www-form-urlencoded)
$('#form').serializeArray(); // [ { name: 'name', value: 'Ada' }, ... ]
jQuery.param({ a: 1, b: [2, 3] }); // "a=1&b%5B%5D=2&b%5B%5D=3"
Global AJAX events
Bound on document, these fire for every jQuery AJAX request on the page — handy for a shared loading
indicator:
$(document).on('ajaxStart', () => $('#spinner').show());
$(document).on('ajaxStop', () => $('#spinner').hide());
$(document).on('ajaxError', (event, jqXHR, settings, thrownError) => log(thrownError));
Modern equivalent
fetch(url, options) returns a real Promise; pair it with AbortController for timeout-style
cancellation. Note fetch only rejects on a network failure — check response.ok for HTTP 4xx/5xx
yourself. Build request bodies with FormData (new FormData(formEl)) or URLSearchParams. Cross-origin
requests are subject to CORS regardless of which API you use — see What is CORS?. For the
full fetch, SSE, and WebSocket reference see Networking, and
Asynchronous JavaScript for promises and async/await.