jQuery AJAX Core focuses on the practical usage of the $.ajax() method. It is used to send asynchronous HTTP requests to the server and handle responses without reloading the web page.
$.ajax() for full controlThe $.ajax() method is the most flexible and powerful AJAX method in jQuery. It allows full configuration of request type, data, response handling, and callbacks.
// Basic structure of jQuery $.ajax() method
$.ajax({
url: "server.php",
type: "GET",
dataType: "json",
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});
// AJAX request to fetch data from server
$("#loadData").click(function() {
$.ajax({
url: "data.txt",
type: "GET",
success: function(data) {
$("#result").html(data);
}
});
});
When the button is clicked, jQuery sends a request to the server. The response is received asynchronously and displayed on the page without refreshing it.
// Interactive AJAX example with button click
$("#loadData").click(function() {
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts/1",
type: "GET",
success: function(data) {
$("#result").html("<strong>Title:</strong> " + data.title);
},
error: function() {
$("#result").html("Error loading data");
}
});
});
beforeSend for loaders