jQuery AJAX Introduction
AJAX (Asynchronous JavaScript and XML) means loading data from a server in the background and updating part of the page — without a full page reload. Search suggestions, "load more" buttons, live chat and saving a form without leaving the page are all AJAX. Despite the name, today the data is almost always JSON, not XML.
jQuery made AJAX popular by wrapping the clumsy, browser-specific XMLHttpRequest API in a few simple functions.
How an AJAX request flows
1. user clicks "Load" ──► 2. jQuery sends an HTTP request (GET /api/users)
│
4. your callback updates ◄── 3. server replies with data (JSON, HTML, text)
the page with the dataThe important word is asynchronous: your code does not stop and wait at step 2. The request runs in the background, the rest of your script continues, and the callback runs later when the response arrives.
jQuery's AJAX methods
| Method | Use it for |
|---|---|
$(sel).load(url) |
Fetch HTML and insert it straight into an element |
$.get(url, data, callback) |
Simple GET request |
$.post(url, data, callback) |
Simple POST request (send data) |
$.getJSON(url, data, callback) |
GET that parses the response as JSON |
$.ajax(options) |
Full control: method, headers, timeouts, error handling |
All of them return a jqXHR object, which works like a promise: .done(), .fail(), .always(), and .then().
A note about these playgrounds
Real AJAX needs a server, but the examples on this site run in a sandboxed frame with no server behind it. To still show real jQuery AJAX calls, the examples use:
- data: URLs — the "file" content is stored in the URL itself:
data:application/json,{"ok":true}. The browser fetches it like any other URL. - A fake server — jQuery lets you plug in a custom transport that answers requests to
/api/...with prepared data after a short delay. Your request code is exactly what you would write against a real backend.
Your first request
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: sans-serif; }
#quote { margin-top: 10px; padding: 10px; border-left: 4px solid #0769ad; background: #eef5fb; min-height: 20px; }
</style>
</head>
<body>
<button id="load">Load quote</button>
<div id="quote">(nothing loaded yet)</div>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
// The "server file": a data: URL that contains JSON
const quoteUrl = "data:application/json," + encodeURIComponent(JSON.stringify({
text: "Simplicity is prerequisite for reliability.",
author: "Edsger W. Dijkstra"
}));
$("#load").on("click", function () {
$("#quote").text("Loading…");
$.getJSON(quoteUrl, function (data) {
$("#quote").text("“" + data.text + "” — " + data.author);
console.log("received:", data);
});
console.log("request sent — this line runs BEFORE the response arrives");
});
</script>
</body>
</html>Look at the order of the console lines: the "request sent" message appears first, even though it is written after $.getJSON. That is asynchrony in action.
A fake server for the examples
The next lessons reuse this small helper. It registers a jQuery transport that intercepts URLs starting with /api/, waits a moment (like a network would), and replies with JSON. Any other URL is handled normally.
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: sans-serif; }
li { margin: 3px 0; }
</style>
</head>
<body>
<button id="users">GET /api/users</button>
<button id="bad">GET /api/missing</button>
<ul id="out"></ul>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
// ---- fake server (stands in for a real backend) ----
const routes = {
"GET /api/users": () => [ { id: 1, name: "Ana" }, { id: 2, name: "Ben" }, { id: 3, name: "Chloe" } ]
};
$.ajaxTransport("+*", function (options) {
if (!options.url.startsWith("/api/")) return; // not ours → normal request
let timer;
return {
send(headers, complete) {
timer = setTimeout(function () {
const route = routes[options.type + " " + options.url.split("?")[0]];
if (route) complete(200, "OK", { text: JSON.stringify(route(options)) });
else complete(404, "Not Found", { text: '{"error":"no such route"}' });
}, 400);
},
abort() { clearTimeout(timer); }
};
});
// ----------------------------------------------------
$("#users").on("click", function () {
$("#out").html("<li>Loading…</li>");
$.getJSON("/api/users")
.done(function (users) {
$("#out").empty().append(users.map(u => $("<li>").text(u.id + ": " + u.name)));
console.log("users:", users.length);
});
});
$("#bad").on("click", function () {
$.getJSON("/api/missing")
.done(() => console.log("unexpected success"))
.fail(function (jqXHR, textStatus) {
$("#out").html("<li>Error " + jqXHR.status + "</li>");
console.log("failed:", jqXHR.status, textStatus);
});
});
</script>
</body>
</html>Everything below the fake-server block is ordinary jQuery AJAX code. In a real project you delete the fake server and the same calls go to your backend.
The same-origin policy
Browsers only let a page read responses from its own origin (same protocol, host and port) unless the other server explicitly allows it with CORS headers (Access-Control-Allow-Origin). If you call someone else's API and see a CORS error in the console, the fix is on the server, not in your jQuery code.
| Situation | Works? |
|---|---|
https://shop.com → https://shop.com/api/cart |
✅ same origin |
https://shop.com → https://api.weather.io/today |
Only if that server sends CORS headers |
Opening your page as file://… |
Most AJAX calls fail — use a local dev server |
Note: jQuery's AJAX functions are not in the slim build. Load
jquery-3.7.1.min.js.
Test yourself
What does "asynchronous" mean for an AJAX call?
- The page reloads when the data arrives
- Your code keeps running while the request is in progress; a callback runs later
- The request blocks the browser until it finishes
- The data is encrypted
Which jQuery method fetches HTML and inserts it into an element in one step?
$.get()$.getJSON().load()$.post()
Your AJAX call to another domain fails with a CORS error. Where is the fix?
- Add
async: false - Use
$.postinstead of$.get - The other server must send CORS headers (or you call it through your own server)
- Update jQuery