jQuery AJAX Introduction
AJAX lets a web page talk to a server and update parts of itself without a full page reload. jQuery wraps the browser's messy AJAX plumbing in a handful of clean, easy methods.
What is AJAX?
AJAX stands for Asynchronous JavaScript And XML. Despite the name, modern AJAX rarely uses XML anymore, HTML and JSON are far more common. The core idea is simple: your page can send a request to a server in the background, receive data back, and then swap that data into the page while the visitor keeps reading or scrolling. Nothing flashes, nothing reloads.
Under the hood, browsers do this with the XMLHttpRequest object (or the newer Fetch API). Writing that by hand means juggling readyState values, status codes, and callbacks. jQuery hides all of that behind short, readable method names so you can focus on what you want, not on the wiring.
- Requests happen in the background, the browser does not freeze while it waits.
- Only the part of the page that needs new data gets updated.
- Less data travels over the network compared to reloading a whole page.
- The result is a faster, smoother experience that feels closer to a native app.
The jQuery AJAX methods
jQuery gives you a small family of methods for talking to the server. The three you will reach for most often are load(), $.get(), and $.post(). All of them are convenient shortcuts built on top of the powerful, fully configurable $.ajax() method.
A first taste of AJAX with $.get()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<button id="loadBtn">Load Greeting</button>
<div id="output"></div>
<script>
$("#loadBtn").click(function() {
$.get("greeting.txt", function(data) {
// 'data' holds whatever the server sent back
$("#output").text(data);
});
});
</script>
</body>
</html>In the example above, when the button is clicked jQuery quietly asks the server for greeting.txt. Once the response arrives, the function you passed runs and places the returned text inside the element with the id output. The visitor never sees a reload.
The same idea with the full $.ajax() method
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="output"></div>
<script>
$.ajax({
url: "greeting.txt",
method: "GET",
success: function(data) {
$("#output").text(data);
},
error: function() {
$("#output").text("Sorry, something went wrong.");
}
});
</script>
</body>
</html>Exercise: jQuery AJAX Intro
What core problem does AJAX solve for web pages?