jQuery $.ajax and Deferreds
$.get, $.post, $.getJSON and .load are all shortcuts. Underneath them is $.ajax(), which takes one options object and gives you full control over the request. This lesson also covers Deferreds — jQuery's promise implementation — which make it easy to combine several asynchronous operations.
$.ajax options
$.ajax({
url: "/api/tasks",
method: "POST", // GET (default), POST, PUT, PATCH, DELETE…
data: JSON.stringify({ title: "Write docs" }),
contentType: "application/json", // what we SEND
dataType: "json", // what we EXPECT back
headers: { "X-CSRF-Token": token },
timeout: 5000 // ms; fails with textStatus "timeout"
})
.done(task => console.log("created", task.id))
.fail((xhr, textStatus) => console.log("failed:", textStatus, xhr.status));| Option | Meaning |
|---|---|
url |
Request URL |
method (alias type) |
HTTP method, default "GET" |
data |
Object (form-encoded, or query string for GET) or a string |
contentType |
Content-Type of the request body; default form encoding |
dataType |
Expected response: "json", "html", "text", "xml", "script" |
headers |
Object of extra request headers |
timeout |
Abort after this many ms |
cache |
false adds _=timestamp to GET URLs to bypass caches |
processData |
false to send data as-is (e.g. FormData) |
beforeSend(xhr) |
Last chance to modify the request; return false to cancel |
xhrFields |
e.g. { withCredentials: true } for cookies on cross-origin requests |
Tip: Set common options once with
$.ajaxSetup({ timeout: 8000, headers: {...} }), but prefer passing options per call in large apps — global settings affect every plugin too.
A complete CRUD example
The fake server below implements a tiny JSON REST API for tasks. Watch the console for each request and response.
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: sans-serif; font-size: 14px; }
#tasks li { margin: 3px 0; }
#tasks li.done span { text-decoration: line-through; color: #888; }
#tasks button { font-size: 11px; margin-left: 6px; }
</style>
</head>
<body>
<input id="title" placeholder="New task"> <button id="add">Add</button>
<ul id="tasks"></ul>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
// ---- fake REST server: /api/tasks ----
const db = [{ id: 1, title: "Learn $.ajax", done: false }];
let nextId = 2;
$.ajaxTransport("+*", function (o) {
if (!o.url.startsWith("/api/tasks")) return;
let t;
return {
send(headers, complete) {
t = setTimeout(() => {
const id = Number(o.url.split("/")[3]);
const body = o.data ? JSON.parse(o.data) : {};
const task = db.find(x => x.id === id);
if (o.type === "GET") return complete(200, "OK", { text: JSON.stringify(db) });
if (o.type === "POST") {
if (!body.title) return complete(422, "Unprocessable", { text: '{"error":"title is required"}' });
const created = { id: nextId++, title: body.title, done: false };
db.push(created);
return complete(201, "Created", { text: JSON.stringify(created) });
}
if (!task) return complete(404, "Not Found", { text: '{"error":"not found"}' });
if (o.type === "PATCH") { Object.assign(task, body); return complete(200, "OK", { text: JSON.stringify(task) }); }
if (o.type === "DELETE") { db.splice(db.indexOf(task), 1); return complete(204, "No Content", { text: "" }); }
}, 200);
},
abort() { clearTimeout(t); }
};
});
// --------------------------------------
function api(method, url, body) {
console.log(method, url, body ? JSON.stringify(body) : "");
return $.ajax({
url, method,
data: body ? JSON.stringify(body) : undefined,
contentType: "application/json",
dataType: method === "DELETE" ? "text" : "json"
});
}
function render(tasks) {
$("#tasks").empty().append(tasks.map(t =>
$("<li>").toggleClass("done", t.done).attr("data-id", t.id).append(
$("<span>").text(t.title),
$("<button class='toggle'>").text(t.done ? "undo" : "done"),
$("<button class='del'>").text("delete"))));
}
const reload = () => api("GET", "/api/tasks").done(render);
$("#add").on("click", function () {
api("POST", "/api/tasks", { title: $("#title").val().trim() })
.done(() => { $("#title").val(""); reload(); })
.fail(xhr => console.log("error", xhr.status, xhr.responseJSON.error));
});
$("#tasks").on("click", "button", function () {
const $li = $(this).closest("li");
const url = "/api/tasks/" + $li.data("id");
const req = $(this).hasClass("del")
? api("DELETE", url)
: api("PATCH", url, { done: !$li.hasClass("done") });
req.done(reload);
});
reload();
</script>
</body>
</html>Click Add with an empty field to see the error path: the server answers 422 and xhr.responseJSON holds the parsed error body.
Deferreds and promises
A Deferred is an object representing a value that will be available later. AJAX calls and animations return its read-only side — a promise. You can also make your own:
| Member | Purpose |
|---|---|
$.Deferred() |
Create a new deferred |
d.resolve(value) / d.reject(err) |
Settle it as success / failure |
d.notify(progress) |
Report progress (.progress() handlers) |
d.promise() |
Read-only view to hand out to callers |
.done(), .fail(), .always(), .progress() |
Attach handlers |
.then(ok, err) |
Chain; returns a new promise |
$.when(p1, p2, …) |
Promise that resolves when all given promises resolve |
Since jQuery 3, Deferreds follow the Promises/A+ standard: .then() handlers run asynchronously, and an exception inside .then() turns into a rejection instead of crashing. They interoperate with native promises and async/await.
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: sans-serif; font-size: 14px; }
#bar { height: 14px; width: 0; background: #0769ad; transition: width .1s; }
#wrap { width: 260px; border: 1px solid #ccc; margin: 8px 0; }
</style>
</head>
<body>
<button id="go">Start fake upload</button> <button id="fail">Upload that fails</button>
<div id="wrap"><div id="bar"></div></div>
<p id="msg"></p>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
// A function that returns a promise — the caller can't resolve it, only listen.
function fakeUpload(shouldFail) {
const d = $.Deferred();
let pct = 0;
const timer = setInterval(function () {
pct += 10;
d.notify(pct);
if (shouldFail && pct === 60) { clearInterval(timer); d.reject("network lost at 60%"); }
if (pct === 100) { clearInterval(timer); d.resolve({ url: "/files/photo.png" }); }
}, 120);
return d.promise();
}
function start(shouldFail) {
$("#msg").text("");
fakeUpload(shouldFail)
.progress(p => $("#bar").css("width", p + "%"))
.then(result => result.url.toUpperCase()) // transform the value
.done(url => { $("#msg").text("Uploaded to " + url); console.log("done:", url); })
.fail(err => { $("#msg").text("Failed: " + err); console.log("fail:", err); })
.always(() => console.log("finished"));
}
$("#go").on("click", () => start(false));
$("#fail").on("click", () => start(true));
</script>
</body>
</html>Waiting for several requests: $.when
$.when() combines promises. With AJAX promises, each done argument is an array [data, textStatus, jqXHR], so take element [0]:
<!DOCTYPE html>
<html>
<body style="font-family: sans-serif; font-size: 14px">
<button id="dash">Load dashboard</button>
<pre id="out"></pre>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
const json = obj => "data:application/json," + encodeURIComponent(JSON.stringify(obj));
const userUrl = json({ name: "Ana", plan: "Pro" });
const statsUrl = json({ projects: 7, storageGb: 3.2 });
$("#dash").on("click", async function () {
// 1) jQuery style
$.when($.getJSON(userUrl), $.getJSON(statsUrl)).done(function (userRes, statsRes) {
const user = userRes[0], stats = statsRes[0];
$("#out").text(user.name + " (" + user.plan + ") has " + stats.projects +
" projects using " + stats.storageGb + " GB");
console.log("$.when version:", userRes[1], statsRes[1]);
});
// 2) the same with native Promise.all + await (jqXHR objects are thenables)
const [user, stats] = await Promise.all([$.getJSON(userUrl), $.getJSON(statsUrl)]);
console.log("await version:", user.name, stats.projects);
});
</script>
</body>
</html>$.when rejects as soon as any promise fails. With await, wrap the call in try { … } catch (xhr) { … } to handle errors.
Global AJAX events
jQuery fires events on document for every AJAX request, which is handy for a global "Loading…" indicator:
$(document)
.on("ajaxStart", () => $("#spinner").show()) // first request started
.on("ajaxStop", () => $("#spinner").hide()) // all requests finished
.on("ajaxError", (e, xhr, settings) => console.warn("failed:", settings.url));Pass global: false in a request's options to keep it from triggering these events.
Test yourself
Which $.ajax option tells jQuery how to parse the RESPONSE?
contentTypedataTypeprocessDatamethod
What does $.when(a, b).done(fn) do?
- Runs
fnwhen either a or b resolves - Runs
fnonce both a and b have resolved - Runs a then b sequentially
- Cancels both if one is slow
Why return d.promise() instead of the Deferred d itself?
- Promises are faster
- So callers can listen but not resolve or reject it
- Deferreds cannot be returned from functions
- It converts it to JSON