What Ajax is
Normally, getting new information from a server means loading a whole new page. Ajax (originally short for Asynchronous JavaScript and XML) lets JavaScript ask the server for data in the background, then update just the part of the page that needs it. Search suggestions, "load more" buttons, live prices, saving a form without leaving the page: all Ajax.
Today the data is nearly always JSON rather than XML, and the server end is usually called an API. In this section the examples use JSONPlaceholder, a free public test API with fake users, posts and to-dos. It allows requests from any site, so the examples run in the live editor.
Your first request
<p id="user">Loading...</p>
<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
<script>
$.getJSON("https://jsonplaceholder.typicode.com/users/1", function (user) {
$("#user").text(user.name + " lives in " + user.address.city);
console.log("name:", user.name);
console.log("email:", user.email);
console.log("company:", user.company.name);
});
</script>name: Leanne Graham
email: Sincere@april.biz
company: Romaguera-Crona$.getJSON(url, callback) sends a GET request to the URL. When the response arrives, jQuery parses the JSON and calls your function with the result, here a JavaScript object with name, email, address and so on.
Asynchronous means "later"
This is the most important idea in Ajax. The request takes time, often tens or hundreds of milliseconds, and the browser does not wait. Code after the call runs immediately:
<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
<script>
let title;
$.getJSON("https://jsonplaceholder.typicode.com/posts/1", function (post) {
title = post.title;
console.log("2. inside the callback:", title.slice(0, 20) + "...");
});
console.log("1. straight after the call:", title);
</script>1. straight after the call: undefined
2. inside the callback: sunt aut facere repe...The line after the call ran first, when title was still undefined. Everything that needs the data must happen inside the callback (or in functions called from it). The Deferreds lesson shows a neater way to write this with async/await.
Sending parameters
The second argument is an optional object of query parameters. jQuery turns it into a query string:
<ul id="todos"></ul>
<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
<script>
$.getJSON("https://jsonplaceholder.typicode.com/todos", { userId: 2, completed: true }, function (todos) {
console.log(todos.length, "completed to-dos for user 2");
todos.slice(0, 3).forEach(task => $("<li>", { text: task.title }).appendTo("#todos"));
console.log("first:", todos[0].title);
});
</script>8 completed to-dos for user 2
first: distinctio vitae autem nihil ut molestias quoThe request went to /todos?userId=2&completed=true. jQuery encodes special characters for you, so values with spaces or & are safe.
Showing results safely
Data from a server is not trusted content, even from your own API: it may contain text a user typed. As in the text and HTML lesson, show it with .text() or by creating elements, never by building an HTML string:
// Safe
$("<li>", { text: post.title }).appendTo("#list");
// Unsafe: post.title could contain markup
$("#list").append("<li>" + post.title + "</li>");A "load more" button
A realistic pattern: load a page of results each time a button is clicked.
<ol id="posts"></ol>
<button id="more">Load more posts</button>
<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
<script>
let page = 0;
const perPage = 3;
$("#more").on("click", function () {
const $btn = $(this).prop("disabled", true).text("Loading...");
page++;
$.getJSON("https://jsonplaceholder.typicode.com/posts", { _page: page, _limit: perPage }, function (posts) {
posts.forEach(post => $("<li>", { text: post.title }).appendTo("#posts"));
$btn.prop("disabled", false).text("Load more posts");
console.log("page", page, "loaded; total shown:", $("#posts li").length);
});
});
</script>page 1 loaded; total shown: 3
page 2 loaded; total shown: 6Disabling the button during the request stops a second click from loading the same page twice. (_page and _limit are JSONPlaceholder's paging parameters; your API will have its own names.)
$.get() for other formats
$.get(url, data, callback) is the general version. jQuery looks at the response's Content-Type and parses JSON automatically; HTML and plain text arrive as strings. $.getJSON() always expects JSON.
There is also .load(), which fetches an HTML page and puts part of it into an element:
// Load the #latest section of /news/ into #sidebar
$("#sidebar").load("/news/ #latest");It is handy on traditional sites that serve HTML fragments from the same domain. Like .html(), it inserts markup, so only load HTML you trust.
Same-origin and CORS
Browsers only let a page read responses from its own origin (protocol, domain and port), unless the other server allows it with CORS headers (Access-Control-Allow-Origin). JSONPlaceholder allows everyone, which is why these examples work. If your request fails with a CORS error in the console, the fix is on the server, not in jQuery.
Common mistakes
- Using the data outside the callback, before it has arrived.
- Building HTML strings from response data.
- Letting users click "load" repeatedly while a request is running.
- Forgetting errors. These examples assume success; the errors lesson shows how to handle failures, which every real request needs.
Exercise
Load the post with id 3 from https://jsonplaceholder.typicode.com/posts/3 and show its title in an h3 and its body in a p. Log the post's userId.
Show one possible answer
<h3 id="t"></h3>
<p id="b"></p>
<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
<script>
$.getJSON("https://jsonplaceholder.typicode.com/posts/3", function (post) {
$("#t").text(post.title);
$("#b").text(post.body);
console.log(post.userId);
});
</script>1Key points
- Ajax means asking the server for data in the background and updating part of the page, without a full reload.
- $.getJSON(url, data, callback) sends a GET request and gives the callback the parsed JSON.
- The request is asynchronous: code after $.getJSON runs before the data arrives, so use the data inside the callback.
- Show data from a server with .text() or by building elements, never by gluing it into HTML.