For working professionals
For fresh graduates
More
2. jQuery Ajax
3. jQuery CSS
12. Jquery Toggle
14. jQuery html()
20. jQuery Animation
Whether you know it or not, you are using Ajax regularly. Wondering how? Well, the social media platforms that you use incorporate Ajax. When you like or comment on a post and the updates happen seamlessly without interrupting your browsing experience, Ajax is at play. The eCommerce website, where you browse through products, add them to your cart, and update your cart without having to refresh the page, is also powered by Ajax.
AJAX, short for Asynchronous JavaScript and XML, is the technology that enables these dynamic and interactive web features. When combined with jQuery, a fast and lightweight JavaScript library, AJAX becomes even more powerful and more accessible to implement. In this tutorial, we will discuss jQuery AJAX Call, focusing on using jQuery AJAX to create powerful and responsive web applications.
Google played a significant role in popularizing AJAX techniques with the launch of Gmail in 2004 and Google Maps in 2005, showing how asynchronous requests create a more desktop-like user experience within web browsers. This all-in-one tutorial will help you understand how to call Ajax in the jQuery function. We will also walk you through some examples to understand this topic better.
AJAX is used to create asynchronous web applications. It enables web pages to update dynamically by exchanging small amounts of data with the server without reloading the entire page, resulting in a smoother and more interactive user experience.
AJAX revolutionized web development by allowing developers to build web applications that feel more like desktop applications. Instead of the traditional request-response model, where each user action triggers a full page reload, AJAX enables partial updates, reducing bandwidth usage and improving responsiveness.
While AJAX can be implemented using native JavaScript, jQuery simplifies the process with its AJAX methods. jQuery abstracts away the complexities of handling XMLHttpRequest objects and provides a cleaner, more intuitive API for making AJAX requests. In the next section, we will talk about the AJAX method in jQuery
Before diving into jQuery AJAX, ensure you have jQuery included in your HTML file. You can download jQuery and include it locally or use a CDN (Content Delivery Network) to include it in your project. Here is how to include jQuery using a CDN:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery AJAX Tutorial</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<!-- Your HTML content here -->
<h1>jQuery AJAX Tutorial</h1>
</body>
</html>
The basic AJAX syntax involves calling a jQuery method ($.ajax(), $.get(), $.post(), etc.) and passing an options object with various settings for the AJAX request. Here is the generic jQuery AJAX example:
$.ajax({
url: 'your-url-here',
method: 'GET', // HTTP method (GET, POST, PUT, DELETE, etc.)
data: {}, // Data to be sent to the server (if any)
dataType: 'json', // Expected data type from the server (json, xml, html, text, etc.)
success: function(response) {
// Callback function for handling successful response
},
error: function(xhr, status, error) {
// Callback function for handling errors
}
});
Let us break down the parameters used in the jQuery AJAX method:
Parameter | Description | Type | Example |
url | Specifies the URL to which the AJAX request will be sent. | String | url: 'https://example.com/api' |
method | Specifies the HTTP request method to be used (e.g., GET, POST, PUT, DELETE, etc.). | String | method: 'POST' |
data | Specifies the data to be sent to the server with the AJAX request. | Object, String, Array | data: { key1: 'value1', key2: 'value2' } |
dataType | Specifies the expected data type of the response from the server (e.g., json, xml, html, text, etc.). | String | dataType: 'json' |
contentType | Specifies the Content-Type header of the request. | String | contentType: 'application/json' |
headers | Specifies additional HTTP headers to be sent with the request. | Object | headers: { 'Authorization': 'Bearer <token>' } |
timeout | Specifies the number of milliseconds after which the request will timeout if no response is received. | Number | timeout: 5000 (5 seconds) |
async | Specifies whether the request should be asynchronous or not. | Boolean | async: false (synchronous request) |
cache | Specifies whether the browser should cache the response. | Boolean | cache: false |
crossDomain | Specifies whether the request is a cross-origin request. | Boolean | crossDomain: true |
jsonp | Specifies whether to use JSONP for cross-origin requests. Only applicable when dataType is 'jsonp'. | String or Boolean | jsonp: 'callback' |
jsonpCallback | Specifies the name of the JSONP callback function. Only applicable when dataType is 'jsonp'. | String | jsonpCallback: 'myCallback' |
beforeSend | A pre-request callback function that can be used to modify the request headers before the request is sent. | Function | beforeSend: function(xhr) { xhr.setRequestHeader('Authorization', 'Bearer <token>'); } |
success | A callback function to be executed when the request is successful. | Function | success: function(response) { console.log('Success:', response); } |
error | A callback function to execute when the request fails. | Function | error: function(xhr, status, error) { console.error('Error:', status, error); } |
complete | A callback function to execute when the request completes, regardless of whether it was successful or failed. | Function | complete: function(xhr, status) { console.log('Request completed:', status); } |
The success function in jQuery AJAX is a callback function that is executed when the AJAX request is completed. It typically receives the data returned by the server as its argument, allowing you to handle and process the response accordingly. Here is a detailed explanation of the jQuery AJAX success function:
success: function(responseData, textStatus, jqXHR) {
// Code to handle successful response
}
$.ajax({
url: 'https://api.example.com/data',
method: 'GET',
dataType: 'json',
success: function(responseData, textStatus, jqXHR) {
// Handle successful response
console.log('Response data:', responseData);
console.log('Status:', textStatus);
},
error: function(jqXHR, textStatus, errorThrown) {
// Handle error
console.error('AJAX Error:', textStatus, errorThrown);
}
});
It's important to handle errors properly in the error callback function, especially when dealing with AJAX requests, to provide a better user experience and debug potential issues.
The success function is only executed if the server responds with a success status code (e.g., 200 OK). If the server returns an error status code (e.g., 404 Not Found), the error function will be invoked instead.
AJAX call in jQuery involves using the $.ajax() function or one of its shorthand methods like $.get(), $.post(), $.getJSON(), etc.
Here is a basic example of how you can make an AJAX call using jQuery:
$.ajax({
url: 'your_url_here',
method: 'GET', // or 'POST', 'PUT', etc. depending on your request type
data: { // optional data to send to the server
param1: 'value1',
param2: 'value2'
},
success: function(response) {
// handle successful response here
console.log(response);
},
error: function(xhr, status, error) {
// handle error here
console.error(xhr.responseText);
}
});
This was a basic jQuery AJAX call example.
You can use the $.ajax() method to make a GET request using jQuery AJAX.
Here is a basic example:
$.ajax({
url: 'https://api.example.com/data',
method: 'GET',
success: function(response) {
console.log('Data retrieved successfully:', response);
},
error: function(xhr, status, error) {
console.error('Error:', error);
}
});
In this example:
Making a POST request is similar to a GET request, but you specify additional parameters such as data to be sent to the server.
Here is an example of jQuery AJAX POST Example:
$.ajax({
url: 'https://api.example.com/save',
method: 'POST',
data: { name: 'John', age: 30 },
success: function(response) {
console.log('Data saved successfully:', response);
},
error: function(xhr, status, error) {
console.error('Error:', error);
}
});
In this example, the data parameter sends JSON data to the server.
JSON (JavaScript Object Notation) is a lightweight data-interchange format widely used for sending data between a client and a server. jQuery automatically parses JSON responses into JavaScript objects. Here is how you can handle JSON data:
$.ajax({
url: 'https://api.example.com/data.json',
method: 'GET',
success: function(response) {
console.log('Data retrieved successfully:', response);
// Process JSON data here
},
error: function(xhr, status, error) {
console.error('Error:', error);
}
});
jQuery also allows you to handle XML responses by using the dataType option. Here is an example:
$.ajax({
url: 'https://api.example.com/data.xml',
method: 'GET',
dataType: 'xml',
success: function(response) {
console.log('XML data retrieved successfully:', response);
// Process XML data here
},
error: function(xhr, status, error) {
console.error('Error:', error);
}
});
It is essential to handle errors gracefully when making AJAX requests. You can use the error callback function to handle errors. Here is a generalized example:
$.ajax({
url: 'https://api.example.com/data',
method: 'GET',
success: function(response) {
console.log('Data retrieved successfully:', response);
},
error: function(xhr, status, error) {
console.error('Error:', error);
}
});
jQuery provides several events that you can use to hook into the AJAX request lifecycle. Some commonly used events include beforeSend, complete, and statusCode. Here is an example:
$.ajax({
url: 'https://api.example.com/data',
method: 'GET',
beforeSend: function(xhr) {
console.log('Request is about to be sent.');
},
success: function(response) {
console.log('Data retrieved successfully:', response);
},
complete: function(xhr, status) {
console.log('Request completed with status:', status);
}
});
By mastering jQuery AJAX, you can create seamless user experiences and enhance the interactivity of your web projects. This tutorial has covered the basics of jQuery AJAX Call, including making requests, handling responses, error handling, and using AJAX events. With this knowledge, you can start integrating AJAX into your web applications and leveraging its capabilities to create richer user experiences.
1. How to call AJAX in jQuery function?
To call AJAX in jQuery, use methods like $.ajax(), $.get(), or $.post().
2. Can I make AJAX requests by jQuery?
Yes, you can make AJAX requests using jQuery using its Ajax methods.
3. How to call AJAX on load in jQuery?
To call AJAX on page load in jQuery, use $(document).ready() function to execute Ajax code.
4. How to pass data in jQuery AJAX call?
To pass data in jQuery AJAX call, use the data parameter in the AJAX settings object.
5. How to call AJAX call in JS?
To make an AJAX call in vanilla JavaScript, use the XMLHttpRequest object or the newer fetch() API.
6. What is AJAX calls?
AJAX calls are asynchronous HTTP requests from the client to the server, enabling data retrieval without reloading the entire page.
7. How to call AJAX without jQuery?
To call AJAX without jQuery, utilize native JavaScript methods like XMLHttpRequest or the fetch() API.
8. How to find AJAX call?
To find AJAX calls in a web application, inspect the network tab of the browser's developer tools.
9. How to call a function in AJAX call?
To call a function in an AJAX call, you can specify it in the success or complete callback functions of the AJAX request.
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.