AJAX and jQuery
AJAX (Asynchronous JavaScript and XML) is the technique of loading data from a server in the background and updating part of a page without reloading it. It was coined in 2005, built on the XMLHttpRequest object, and made easy for a decade by jQuery, the library behind the famous $(). Today fetch, querySelector and classList do the same jobs natively, but millions of pages and many internal business tools still use the older code. This lesson teaches you to read it and translate it, not to write new code with it.
In One Minute
- "AJAX" now just means "requests from JavaScript"; modern AJAX uses
fetch. XMLHttpRequest(XHR) is the older request API: callback-based, more verbose, still supported everywhere.- jQuery wraps the DOM and AJAX:
$("#id"),.text(),.addClass(),.on(),$.ajax(). Each has a native equivalent. - JSONP loaded cross-origin data through
<script>tags before CORS existed. It's insecure; never use it in new code. - When you meet these in a codebase, keep it working, and migrate piece by piece when you touch it.
XMLHttpRequest
XMLHttpRequest predates promises, so it uses events and callbacks:
[{ "name": "Navika", "amount": 120 }, { "name": "Advitha", "amount": 45 }]<script>
const xhr = new XMLHttpRequest();
xhr.open("GET", "/api/payments.json");
xhr.responseType = "json";
xhr.addEventListener("load", () => {
if (xhr.status >= 200 && xhr.status < 300) {
console.log("XHR:", xhr.status, xhr.response.length, "payments");
} else {
console.log("XHR HTTP error", xhr.status);
}
});
xhr.addEventListener("error", () => console.log("XHR network error"));
xhr.send();
console.log("request sent");
</script>request sent
XHR: 200 2 paymentsThe same request with fetch:
<script type="module">
const res = await fetch("/api/payments.json");
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const payments = await res.json();
console.log("fetch:", res.status, payments.length, "payments");
</script>fetch: 200 2 paymentsXMLHttpRequest | fetch |
|---|---|
xhr.open(method, url); xhr.send(body) | fetch(url, { method, body }) |
load, error, readystatechange events | A promise, works with await |
xhr.status, xhr.responseText, xhr.response | res.status, await res.text(), await res.json() |
xhr.setRequestHeader(name, value) | headers: { name: value } |
xhr.abort() | AbortController |
xhr.upload.onprogress | Upload progress: still an XHR advantage |
You'll often see the older onreadystatechange style, checking xhr.readyState === 4 (done). One XHR feature fetch still lacks in most browsers is upload progress events, which is why some file-upload code keeps using XHR.
jQuery
jQuery (first released in 2006) smoothed over differences between browsers and offered a compact API. Its central function is $ (also called jQuery), which selects elements and returns a jQuery object wrapping them, with chainable methods that act on every selected element.
Since jQuery can't be loaded in the checker (no internet), the jQuery examples below are shown without output; each is paired with checked native code that does the same.
Selecting and Changing
$(".fee").addClass("highlight");
$("#status").text("Saved");
$("#amount").val("120");
$("li.unpaid").css("color", "crimson").attr("data-flag", "late");
$("#details").hide();
$("#list").append("<li>New</li>"); // builds HTML from a string: careful with user data!<ul id="list"><li class="fee unpaid">Books</li></ul>
<p id="status"></p><input id="amount"><div id="details">Info</div>
<script>
document.querySelectorAll(".fee").forEach((el) => el.classList.add("highlight"));
document.querySelector("#status").textContent = "Saved";
document.querySelector("#amount").value = "120";
for (const li of document.querySelectorAll("li.unpaid")) {
li.style.color = "crimson";
li.setAttribute("data-flag", "late");
}
document.querySelector("#details").hidden = true;
const li = document.createElement("li");
li.textContent = "New";
document.querySelector("#list").append(li);
console.log(document.querySelector(".fee").className, document.querySelector("#status").textContent);
console.log(document.querySelector("#list").children.length, document.querySelector("#details").hidden);
</script>fee unpaid highlight Saved
2 true| jQuery | Native JavaScript |
|---|---|
$("#id"), $(".cls") | document.querySelector, querySelectorAll |
.text(t) / .html(h) | .textContent = t / .innerHTML = h (unsafe with user data) |
.val() | .value |
.addClass / .removeClass / .toggleClass | .classList.add / remove / toggle |
.attr(name, v) / .data(key) | .setAttribute(name, v) / .dataset.key |
.css(prop, v) | .style.prop = v |
.show() / .hide() | .hidden = false / true (or a class) |
.append, .prepend, .remove() | .append, .prepend, .remove() |
.closest(sel), .parent(), .find(sel) | .closest(sel), .parentElement, .querySelectorAll(sel) |
.each(fn) | for...of or forEach |
Events
$("#pay").on("click", function () { /* this is the element */ });
$("#rows").on("click", ".remove", function () { $(this).closest("tr").remove(); }); // delegation
$(document).ready(function () { /* DOM ready */ }); // or $(function () { ... })| jQuery | Native |
|---|---|
.on("click", fn) | .addEventListener("click", fn) |
.on("click", ".remove", fn) (delegation) | addEventListener("click", (e) => { const el = e.target.closest(".remove"); ... }) |
.off("click", fn) | .removeEventListener("click", fn) |
$(document).ready(fn) | A defer or module script, or DOMContentLoaded |
Note that jQuery handlers written with function use this for the element; when converting to arrow functions, use event.currentTarget instead.
$.ajax
$.ajax({ url: "/api/payments", method: "GET", dataType: "json" })
.done(function (payments) { render(payments); })
.fail(function (xhr) { showError(xhr.status); });
$.getJSON("/api/payments", render);
$.post("/api/payments", { name: "Advitha", amount: 45 });These become fetch calls with await and an ok check, as in the fetch lesson. One difference to watch for: $.post with an object sends form-encoded data, not JSON; the native equivalent is fetch(url, { method: "POST", body: new URLSearchParams(data) }).
JSONP
Before CORS (around 2010), browsers had no way for a page to read data from another origin. JSONP ("JSON with padding") worked around it: a <script> tag can load code from any origin, so the server wrapped its JSON in a function call:
<script>
function showRates(data) { console.log(data.rate); }
</script>
<!-- The server replies with JavaScript: showRates({"rate": 1.08}) -->
<script src="https://api.rates.example/usd?callback=showRates"></script>It works only for GET, has no proper error handling, and is dangerous: you are running whatever code the other server sends, with full access to your page. If that server is compromised, so is your site. Modern servers use CORS instead; modern pages use fetch.
Migrating Old Code
| You find | Replace with |
|---|---|
new XMLHttpRequest() | fetch with await and an ok check |
$.ajax, $.get, $.getJSON, $.post | fetch |
JSONP (?callback=) | A CORS-enabled endpoint and fetch, or a call through your own server |
$(selector) and DOM helpers | querySelector(All), classList, textContent |
$(document).ready | defer or type="module" |
.html(userData) | textContent or createElement |
In Practice
A real migration from the Fee Tracker's old admin page. The jQuery version:
$(function () {
$.getJSON("/api/payments.json", function (payments) {
$.each(payments, function (i, p) {
$("#list").append("<li>" + p.name + ": $" + p.amount + "</li>");
});
$("#count").text(payments.length + " payments");
});
});The native version does the same, safely, with error handling the original lacked:
<ul id="list"></ul><p id="count"></p>
<script type="module">
try {
const res = await fetch("/api/payments.json");
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const payments = await res.json();
document.querySelector("#list").append(...payments.map((p) => {
const li = document.createElement("li");
li.textContent = `${p.name}: $${p.amount}`;
return li;
}));
document.querySelector("#count").textContent = `${payments.length} payments`;
} catch (err) {
document.querySelector("#count").textContent = `Couldn't load payments (${err.message})`;
}
console.log(document.querySelector("#count").textContent, "|", document.querySelector("#list").textContent);
</script>2 payments | Navika: $120Advitha: $45Common Mistakes
Writing new code with XHR or jQuery out of habit. Native APIs cover nearly everything with no dependency.
Translating $.post(data) to a JSON fetch. jQuery sends form encoding; the server may expect that. Match the format.
Keeping JSONP. It runs remote code in your page. Replace it.
Copying .html(userData) patterns into native code as innerHTML. Use textContent.
Practice
Challenge: Translate this jQuery snippet into native JavaScript: $("#rows").on("click", ".paid", function () { $(this).closest("tr").addClass("done"); });. Test it by clicking a button.
Show solution
<table><tbody id="rows">
<tr><td>Navika</td><td><button class="paid">Paid</button></td></tr>
<tr><td>Advitha</td><td><button class="paid">Paid</button></td></tr>
</tbody></table>
<script>
document.querySelector("#rows").addEventListener("click", (event) => {
const button = event.target.closest(".paid");
if (!button) return;
button.closest("tr").classList.add("done");
console.log(button.closest("tr").cells[0].textContent, "marked done");
});
</script>Advitha marked doneKey Takeaways
| Legacy | Modern |
|---|---|
XMLHttpRequest | fetch |
$("#id") | document.querySelector("#id") |
.on("click", sel, fn) | addEventListener + closest(sel) |
$.getJSON(url, fn) | const data = await (await fetch(url)).json() |
| JSONP | CORS + fetch |
Was this tutorial helpful?