Module 16 · Lesson 6
AJAX with jQuery
Talk to a server without reloading the page — the feature that put the "AJAX" in jQuery.
Introduction
AJAX (Asynchronous JavaScript and XML) lets a page request data from a server in the background and update part of the UI without a full reload. jQuery wrapped the clunky XMLHttpRequest API into a few clean methods that worked the same in every browser — a major reason for its popularity.
You learned the modern equivalent,
fetch(), in module 14. jQuery's AJAX methods do the same job with a slightly different API you'll meet in older codebases.Theory
The methods
$.ajax(options)— the full-control method; configure URL, method, data, headers, and callbacks.$.get(url, cb)— shorthand for a GET request.$.post(url, data, cb)— shorthand for a POST request.$.getJSON(url, cb)— GET that automatically parses a JSON response.
Handling responses
Modern jQuery AJAX returns a promise-like object, so you chain handlers:
$.getJSON('https://api.example.com/users')
.done(function (data) { /* success */ })
.fail(function (err) { /* error */ })
.always(function () { /* runs either way */ });
Or with $.ajax:
$.ajax({
url: 'https://api.example.com/users',
method: 'GET',
dataType: 'json'
}).done(handleSuccess).fail(handleError);
Security: render server data with
.text() (escaped), not .html(), unless you fully trust and sanitize the source. API responses can contain attacker-controlled strings.Real World Example
Click below to fetch a post from the public JSONPlaceholder API. The title and body are inserted with .text(), so any markup in the response is shown as literal text — never executed:
$('#loadBtn').on('click', function () {
$.getJSON('https://jsonplaceholder.typicode.com/posts/1')
.done(function (post) {
$('#postTitle').text(post.title); // .text() — XSS safe
$('#postBody').text(post.body);
})
.fail(function () {
$('#postTitle').text('Request failed.');
});
});
No data yet.
Click the button to fetch from the API.
Common Mistakes
- Expecting synchronous results. AJAX is asynchronous — read the data inside the callback, not on the line after the call.
- Ignoring errors. Always attach
.fail()(or anerrorcallback) so failures don't fail silently. - Rendering responses with
.html(). Untrusted API data can carry script payloads — use.text(). - CORS surprises. Browsers block cross-origin requests unless the server sends the right headers.
Best Practices
- Use
$.getJSONfor simple JSON GETs; reach for$.ajaxwhen you need headers, methods, or fine control. - Always handle the error case and show the user a clear message.
- Show a loading indicator while the request is in flight; clear it in
.always(). - For new code, consider native
fetch()— but know the jQuery equivalents for maintaining legacy apps.
Practice Exercise
- Use
$.getJSONto fetchhttps://jsonplaceholder.typicode.com/users. - In
.done(), loop the array and append each user's name to a list with.text(). - Add a
.fail()handler that shows an error message. - Add a loading message that clears in
.always().
Assignment
Build a small "user lookup" tool:
- An input for a user id (1–10) and a "Fetch" button.
- On click, call
$.getJSON('https://jsonplaceholder.typicode.com/users/' + id). - Render the user's name, email, and city — each set with
.text(). - Handle invalid ids and network errors gracefully with
.fail().
Security reminder: every field you display comes from the API — set it with
.text(), never .html().Interview Questions
- What is AJAX? — A technique for exchanging data with a server asynchronously so the page updates without a full reload.
- What's the difference between
$.getand$.getJSON? —$.getJSONautomatically parses the response as JSON;$.getreturns it as-is (or perdataType). - How do you handle a failed request? — Attach
.fail()(or anerrorcallback in$.ajax). - How do you safely display API data? — Use
.text()so the data is escaped, guarding against XSS. - What's the modern vanilla equivalent? — The
fetch()API with promises / async-await.
Additional Resources
- api.jquery.com/jQuery.ajax — the
$.ajaxreference - api.jquery.com/jQuery.getJSON — the
$.getJSONreference - jsonplaceholder.typicode.com — a free fake REST API for testing