Introduction to AJAX
In this page:
$.ajax({
url: "url",
method: "GET",
success: function(data) {
// use data
},
error: function() {
// handle failure
}
});
What is AJAX?
AJAX lets a page request data from a server in the background without a full page reload; jQuery wraps the browser's raw AJAX API in a simpler, more consistent one. This is what makes features like live search or infinite scroll possible without navigating away.
Example: What is AJAX?
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<style>
button { padding:6px 14px; margin:4px; background:#2c6aa0; color:white; border:none; border-radius:4px; cursor:pointer; }
#resetBtn { background:white; color:#2c6aa0; border:1px solid #2c6aa0; }
#output { margin-top:10px; padding:8px; border:1px solid #ccc; border-radius:4px; background:#f7f7f7; font-family:monospace; min-height:24px; }
#demo :where(p, div, span, li, h1, h2, h3, h4, td, th, blockquote, label, section, article, aside) { border:1px solid #4a7fb5; background:#eaf2fb; padding:6px 10px; margin:4px 0; border-radius:4px; }
#demo :where(ul, ol) { border:1px dashed #888; background:#fafafa; padding:8px 8px 8px 32px; margin:6px 0; }
#demo :where(table) { border-collapse:collapse; }
#demo :where(td, th) { border-radius:0; }
#demo :where(input, select, textarea) { margin:4px 0; }
</style>
</head>
<body>
<button id="resetBtn">Reset</button>
<section id="demo">
<button id="btn">Load</button>
</section>
<div id="output"></div>
<script>
var original = $("#demo").html();
function init() {
$("#btn").on("click", function() {
$.ajax({url: "data.php", success: function(data) {
$("#output").append($("<div>").text("Received: " + JSON.stringify(data)));
}});
});
}
init();
$("#resetBtn").click(function() {
$("#demo").html(original);
$("#output").empty();
init();
});
</script>
</body>
</html>
AJAX Method
The $.ajax() method accepts a configuration object with options such as url, method, data, success, and error, giving you full control over exactly how the request is made. It's the most flexible AJAX method jQuery provides, underlying the shorthand methods like get() and post().
Example: AJAX Method
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<style>
button { padding:6px 14px; margin:4px; background:#2c6aa0; color:white; border:none; border-radius:4px; cursor:pointer; }
#resetBtn { background:white; color:#2c6aa0; border:1px solid #2c6aa0; }
#output { margin-top:10px; padding:8px; border:1px solid #ccc; border-radius:4px; background:#f7f7f7; font-family:monospace; min-height:24px; }
</style>
</head>
<body>
<button id="runBtn">Run</button>
<button id="resetBtn">Reset</button>
<div id="output"></div>
<script>
$("#runBtn").click(function() {
$("#output").empty();
$("#output").append($("<div>").text("Sending request..."));
$.ajax({
url: "data.php",
method: "GET",
success: function(data) { $("#output").append($("<div>").text(JSON.stringify(data))); },
error: function() { $("#output").append($("<div>").text("Request failed")); }
});
});
$("#resetBtn").click(function() {
jQuery(document).off();
$("#output").empty();
});
</script>
</body>
</html>
Handling Returned Data
A successful request passes its returned data to the success callback, where you can use it to update the page -- inserting it into the DOM, filling a table, or updating a counter. What that data looks like depends entirely on what the server sends back.
Example: Handling Returned Data
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<style>
button { padding:6px 14px; margin:4px; background:#2c6aa0; color:white; border:none; border-radius:4px; cursor:pointer; }
#resetBtn { background:white; color:#2c6aa0; border:1px solid #2c6aa0; }
#output { margin-top:10px; padding:8px; border:1px solid #ccc; border-radius:4px; background:#f7f7f7; font-family:monospace; min-height:24px; }
#demo :where(p, div, span, li, h1, h2, h3, h4, td, th, blockquote, label, section, article, aside) { border:1px solid #4a7fb5; background:#eaf2fb; padding:6px 10px; margin:4px 0; border-radius:4px; }
#demo :where(ul, ol) { border:1px dashed #888; background:#fafafa; padding:8px 8px 8px 32px; margin:6px 0; }
#demo :where(table) { border-collapse:collapse; }
#demo :where(td, th) { border-radius:0; }
#demo :where(input, select, textarea) { margin:4px 0; }
</style>
</head>
<body>
<button id="runBtn">Run</button>
<button id="resetBtn">Reset</button>
<section id="demo">
<ul id="list"></ul>
</section>
<div id="output"></div>
<script>
var original = $("#demo").html();
$(document).ajaxError(function(event, xhr, settings) {
$("#output").append($("<div>").text("Request failed: " + settings.url));
});
$("#runBtn").click(function() {
$("#output").empty();
$("#output").append($("<div>").text("Sending request..."));
$.ajax({url: "data.php", success: function(data) {
$("#list").append("<li>" + data.message + "</li>");
}});
});
$("#resetBtn").click(function() {
$("#demo").html(original);
jQuery(document).off();
$("#output").empty();
});
</script>
</body>
</html>
AJAX Error Handling
Network requests can fail for many reasons -- a dropped connection, a server error, a bad URL -- so the error callback lets you show a friendly message instead of leaving the page silently broken. Handling this case is just as important as handling success.
Example: AJAX Error Handling
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<style>
button { padding:6px 14px; margin:4px; background:#2c6aa0; color:white; border:none; border-radius:4px; cursor:pointer; }
#resetBtn { background:white; color:#2c6aa0; border:1px solid #2c6aa0; }
#output { margin-top:10px; padding:8px; border:1px solid #ccc; border-radius:4px; background:#f7f7f7; font-family:monospace; min-height:24px; }
</style>
</head>
<body>
<button id="runBtn">Run</button>
<button id="resetBtn">Reset</button>
<div id="output"></div>
<script>
$("#runBtn").click(function() {
$("#output").empty();
$("#output").append($("<div>").text("Sending request..."));
$.ajax({
url: "data.php",
success: function(data) { $("#output").append($("<div>").text(JSON.stringify(data))); },
error: function() { $("#output").append($("<div>").text("Something went wrong, please try again")); }
});
});
$("#resetBtn").click(function() {
jQuery(document).off();
$("#output").empty();
});
</script>
</body>
</html>
AJAX in a Small Project
AJAX is useful for small interactive pages where loading everything up front would be wasteful, like fetching extra details only when the user clicks a 'show more' button. This keeps the initial page load light while still allowing rich, on-demand interactivity.
Example: AJAX in a Small Project
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<style>
button { padding:6px 14px; margin:4px; background:#2c6aa0; color:white; border:none; border-radius:4px; cursor:pointer; }
#resetBtn { background:white; color:#2c6aa0; border:1px solid #2c6aa0; }
#output { margin-top:10px; padding:8px; border:1px solid #ccc; border-radius:4px; background:#f7f7f7; font-family:monospace; min-height:24px; }
#demo :where(p, div, span, li, h1, h2, h3, h4, td, th, blockquote, label, section, article, aside) { border:1px solid #4a7fb5; background:#eaf2fb; padding:6px 10px; margin:4px 0; border-radius:4px; }
#demo :where(ul, ol) { border:1px dashed #888; background:#fafafa; padding:8px 8px 8px 32px; margin:6px 0; }
#demo :where(table) { border-collapse:collapse; }
#demo :where(td, th) { border-radius:0; }
#demo :where(input, select, textarea) { margin:4px 0; }
</style>
</head>
<body>
<button id="resetBtn">Reset</button>
<section id="demo">
<button id="showMore">Show More</button>
<div id="details"></div>
</section>
<div id="output"></div>
<script>
var original = $("#demo").html();
function init() {
$("#showMore").on("click", function() {
$.ajax({url: "data.php", success: function(data) {
$("#details").text(data.message);
}});
});
}
init();
$("#resetBtn").click(function() {
$("#demo").html(original);
$("#output").empty();
init();
});
</script>
</body>
</html>
- Expecting
$.ajax()to return the data directly likeconst d = $.ajax(...), when the request is asynchronous and the data only arrives insuccessor.done(). - Using code that depends on the response right after the
$.ajax()call, which runs before the response arrives. - Forgetting an
errorcallback so failed requests such as a badurlfail silently and the user sees nothing.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: