jQueryintermediate 8 min
Load data from a server without reloading the page, using $.getJSON, $.ajax and $.post.
How to request data in the background with $.getJSON and $.ajax, show it on the page, and handle success, failure and completion.
AJAX (Asynchronous JavaScript and XML) is what lets a page update without a full reload: search suggestions, live comments, "load more" buttons. jQuery made it a one-liner long before fetch existed, and a huge amount of existing code still uses it.
The main helpers:
$.getJSON(url): GET a URL and parse the JSON reply.$.get(url) and $.post(url, data): plain GET and POST.$.ajax({ url, method, data, dataType }): the full-control version.They return a promise-like object. You attach handlers:
.done(function (data) { ... }): runs when the request succeeds..fail(function () { ... }): runs when it fails..always(function () { ... }): runs in both cases.The request is asynchronous: the line after $.getJSON(...) runs immediately, and the callback runs later, when the data arrives.
Loading... right away.$.getJSON(url) starts the request and returns at once..done runs. We empty the list, then loop with $.each and append an item per user.Loaded 2 users, and the list shows Asha from Pune and Ravi from Delhi..fail would run and show an error message instead.Click Load users in the preview. Then add a third user to the JSON and click again.
.done runs..fail handler, so users see nothing when it breaks..text() for user content.$.getJSON, $.get, $.post and $.ajax fetch and send data in the background..done, .fail and .always.Next: moving around the DOM and chaining commands.
<button id="load">Load users</button>
<ul id="users"></ul>
<p id="status"></p>
<script>
const json = JSON.stringify([
{ name: "Asha", city: "Pune" },
{ name: "Ravi", city: "Delhi" },
]);
const url = "data:application/json," + encodeURIComponent(json);
$("#load").on("click", function () {
$("#status").text("Loading...");
$.getJSON(url)
.done(function (users) {
$("#users").empty();
$.each(users, function (i, u) {
$("#users").append("<li>" + u.name + " from " + u.city + "</li>");
});
$("#status").text("Loaded " + users.length + " users");
})
.fail(function () {
$("#status").text("Something went wrong");
});
});
</script>