How to Use jQuery Ajax to Send and Receive JSON Data (Complete Guide with Examples)
Introduction
Ajax (Asynchronous JavaScript and XML) is a technique used in web development to send and receive data asynchronously from a server without refreshing the page. jQuery Ajax simplifies this process by providing easy-to-use methods for handling HTTP requests.
In this tutorial, you will learn:
- How to make GET and POST requests using jQuery Ajax
- How to send and receive JSON data
- How to handle errors properly
- How jQuery Ajax compares with modern alternatives like Fetch API
1. What is jQuery Ajax?
💡 Why Use Ajax?
- ✅ Faster user experience: No need to reload the page.
- ✅ Efficient data communication: Only necessary data is sent and received.
- ✅ Widely used in web applications: Works with APIs and databases.
💡 What is JSON?
JSON (JavaScript Object Notation) is the most common format for data exchange between a server and a client.
Example of JSON Data:
1
2
3
4
5
|
{
"id": 1,
"name": "John Doe",
"email": "john.doe@example.com"
}
|
💡 JSON is lightweight, human-readable, and easy to parse in JavaScript.
2. jQuery Ajax GET Request with JSON Response
The GET request retrieves data from the server.
🔹 Example 1: Fetching JSON Data from an API
1
2
3
4
5
6
7
8
9
10
11
12
13
|
$.ajax({
url: "https://jsonplaceholder.typicode.com/users/1",
type: "GET",
dataType: "json", // Expect JSON response
success: function(response) {
console.log("User Data:", response);
$("#user-name").text(response.name);
$("#user-email").text(response.email);
},
error: function(xhr, status, error) {
console.error("Error:", error);
}
});
|
🔹 Explanation
- url: API endpoint returning JSON data.
- type: "GET": Specifies a GET request.
- dataType: "json": Ensures the response is treated as JSON.
- success: Runs when the request is successful.
- error: Runs when the request fails.
🔹 Example 2: Fetching a List of Users and Displaying in HTML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
$.ajax({
url: "https://jsonplaceholder.typicode.com/users",
type: "GET",
dataType: "json",
success: function(users) {
let userList = "";
users.forEach(function(user) {
userList += `<li>${user.name} - ${user.email}</li>`;
});
$("#user-list").html(userList);
},
error: function(xhr, status, error) {
console.error("Error:", error);
}
});
|
🛠 HTML Code for Displaying Users
1
2
|
<ul id="user-list"></ul>
|
📌 Best Practices:
- Always handle the error response properly.
- Display data dynamically in the UI.
3. jQuery Ajax POST Request with JSON Data
A POST request is used to send data to a server.
🔹 Example 3: Sending JSON Data via jQuery Ajax POST Request
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts",
type: "POST",
contentType: "application/json", // Specify JSON format
data: JSON.stringify({
title: "New Post",
body: "This is a sample post created using jQuery Ajax.",
userId: 1
}),
success: function(response) {
console.log("Post Created:", response);
alert("Post successfully created!");
},
error: function(xhr, status, error) {
console.error("Error:", error);
}
});
|
🔹 Explanation
- contentType: "application/json": Ensures the request body is JSON.
- data: JSON.stringify({...}): Converts JavaScript object to JSON format.
- success: Runs when the request is successful.
- error: Catches and logs any errors.
4. Handling Errors in jQuery Ajax
Error handling is critical when working with Ajax requests.
🔹 Example 4: Handling Different HTTP Status Codes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
$.ajax({
url: "https://jsonplaceholder.typicode.com/invalid-url",
type: "GET",
dataType: "json",
success: function(response) {
console.log(response);
},
error: function(xhr, status, error) {
console.error("Error Code:", xhr.status);
console.error("Error Message:", error);
if (xhr.status === 404) {
alert("Resource not found!");
} else if (xhr.status === 500) {
alert("Server error, please try again later.");
} else {
alert("An unknown error occurred.");
}
}
});
|
📌 Best Practices:
- Check xhr.status for specific errors (e.g., 404 Not Found, 500 Server Error).
- Display user-friendly error messages.
5. jQuery Ajax vs Fetch API for JSON Requests
Feature | jQuery Ajax | Fetch API |
Simplicity | ✅ Easy to use | ⚠️ Requires more setup |
JSON Handling | ✅ Built-in dataType option | ⚠️ Requires response.json() |
Error Handling | ✅ Supports error callback | ⚠️ Needs catch() |
Browser Support | ✅ Works in all browsers | ⚠️ Older browsers need polyfill |
📌 Fetch API Alternative
1
2
3
4
|
fetch("https://jsonplaceholder.typicode.com/users/1")
.then(response => response.json())
.then(data => console.log("User Data:", data))
.catch(error => console.error("Error:", error));
|
6. Conclusion
By now, you have learned: ✅ How to make GET and POST requests using jQuery Ajax
✅ How to send and receive JSON data
✅ How to handle errors properly
✅ The differences between jQuery Ajax and Fetch API
🚀 Next Steps:
- Try making a PUT request to update data.
- Learn how to use async/await with Fetch API.
- Explore modern alternatives like Axios.