In this tutorial, we're going to discuss how to make AJAX calls using jQuery. AJAX stands for Asynchronous JavaScript and XML, a technique used to update parts of a web page, without reloading the whole page.
You will learn how to use jQuery's AJAX methods to send HTTP requests from your client-side application to your server-side code.
Basic understanding of JavaScript, jQuery, and HTTP is beneficial.
jQuery provides several methods for AJAX functionality. The most commonly used method is the $.ajax()
method. It performs an AJAX (asynchronous HTTP) request. This method is flexible and offers a lot of functionality.
$.ajax({
url: 'url',
method: 'GET',
success: function(data) {
console.log(data);
}
});
error
callback.// Make a GET request to the provided URL
$.ajax({
url: 'http://api.example.com/data', // the URL to make the request to
method: 'GET', // the HTTP method to use for the request
success: function(data) { // the function to run when the request succeeds
console.log(data); // log the data returned from the server
},
error: function(error) { // the function to run if the request fails
console.error('Error:', error);
}
});
// Make a POST request to the provided URL
$.ajax({
url: 'http://api.example.com/data', // the URL to make the request to
method: 'POST', // the HTTP method to use for the request
data: {
name: 'John',
age: 30,
}, // the data to send to the server
success: function(response) { // the function to run when the request succeeds
console.log(response); // log the response from the server
},
error: function(error) { // the function to run if the request fails
console.error('Error:', error);
}
});
The $.ajax()
method returns a Promise that we can use to chain callbacks.
In this tutorial, we learned how to make AJAX calls using jQuery. We discussed the $.ajax()
method, how to handle successes and failures, and how to send data to the server.
Start making AJAX calls in your own projects. Experiment with different types of requests and data.
Make an AJAX GET request to a public API of your choice.
Make an AJAX POST request to a public API. Send some data in the request.
Exercise 1
$.ajax({
url: 'https://api.github.com/users/octocat',
method: 'GET',
success: function(data) {
console.log(data);
},
error: function(error) {
console.error('Error:', error);
}
});
In this example, we're making a GET request to GitHub's API to get information about a user.
Exercise 2
$.ajax({
url: 'https://jsonplaceholder.typicode.com/posts',
method: 'POST',
data: {
title: 'foo',
body: 'bar',
userId: 1,
},
success: function(data) {
console.log(data);
},
error: function(error) {
console.error('Error:', error);
}
});
Here, we're making a POST request to JSONPlaceholder's API, a fake online REST API for testing. We're sending data with our request, which includes a title, body, and userId.