AJAX in jQuery allows web pages to communicate with a server asynchronously without reloading the page. jQuery simplifies AJAX setup using built-in helper methods and global configuration.
jQuery provides the $.ajax() method for full control, along with shortcuts like $.get() and $.post().
// Basic AJAX setup using jQuery
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts/1",
method: "GET",
success: function(response) {
console.log(response);
}
});
The request sends a GET call to the server and logs the response without refreshing the page.
// Interactive AJAX call on button click
$("#loadData").click(function() {
$("#result").text("Loading...");
$.get("https://jsonplaceholder.typicode.com/posts/1", function(data) {
$("#result").html("<strong>Title:</strong> " + data.title +
"<br><br><strong>Body:</strong> " + data.body);
}).fail(function() {
$("#result").text("Error: Could not fetch data.");
});
});
error callbacks