π AJAX β Send PUT Request: Update Data Asynchronously Using JavaScript
π§² Introduction β Why Use AJAX PUT Requests?
In modern web development, we often need to update existing data without reloading the page. Thatβs where the AJAX PUT request comes into play. According to RESTful API standards, the PUT method is used to update an entire resourceβand AJAX lets you send such updates asynchronously.
Whether you’re modifying a user profile, updating settings, or syncing data with an API, sending a PUT request with AJAX helps you build faster, smoother, and more responsive applications.
π― In this guide, youβll learn:
- How PUT differs from POST
- How to send a PUT request using both
XMLHttpRequest
andfetch()
- Practical examples with JSON payloads
- Best practices and error handling
π What Is a PUT Request in AJAX?
A PUT request is an HTTP method used to update an existing resource on the server. It typically includes a JSON payload and is targeted at a specific URL that identifies the resource (e.g., /users/123
).
π¦ PUT vs POST β What’s the Difference?
Feature | POST | PUT |
---|---|---|
Action | Create a new resource | Update an existing resource |
Target | Often generic (/users ) | Specific (/users/123 ) |
Idempotent | β No (multiple calls = multiple entries) | β Yes (multiple calls = same result) |
Use Case | User registration | User profile update |
π€ Send PUT Request Using XMLHttpRequest
var xhr = new XMLHttpRequest();
xhr.open("PUT", "https://api.example.com/users/123", true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log("Update success:", xhr.responseText);
} else {
console.error("Error:", xhr.status);
}
}
};
const updatedData = JSON.stringify({
name: "Jane Doe",
email: "jane.doe@example.com"
});
xhr.send(updatedData);
β
This updates the user with ID 123
using a PUT request and JSON data.
π Send PUT Request Using fetch()
(Modern Approach)
fetch("https://api.example.com/users/123", {
method: "PUT",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name: "Jane Doe",
email: "jane.doe@example.com"
})
})
.then(response => {
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
return response.json();
})
.then(data => {
console.log("User updated:", data);
})
.catch(error => {
console.error("Update failed:", error);
});
β
This modern, clean method uses fetch()
and works well with RESTful APIs.
π§ͺ Example β PUT Request in Real-World Scenario
Let’s say you have a user profile update form:
<input type="text" id="username" value="John" />
<input type="email" id="email" value="john@example.com" />
<button id="saveBtn">Update Profile</button>
π§ JavaScript:
document.getElementById("saveBtn").addEventListener("click", function () {
const name = document.getElementById("username").value;
const email = document.getElementById("email").value;
fetch("https://api.example.com/users/123", {
method: "PUT",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ name, email })
})
.then(res => res.json())
.then(data => alert("Profile updated!"))
.catch(err => console.error("Error:", err));
});
β οΈ Common Mistakes to Avoid
β Mistake | β Fix |
---|---|
Using POST instead of PUT for updates | Use PUT for full updates, PATCH for partial ones |
Sending raw objects | Always use JSON.stringify() to serialize payload |
Forgetting content-type header | Set Content-Type: application/json |
Ignoring server errors | Always handle .catch() or xhr.status properly |
π Summary β Recap & Takeaways
The AJAX PUT request allows developers to update server-side data asynchronously using JavaScript. Whether you’re using XMLHttpRequest
or the newer fetch()
API, PUT enables you to keep the user interface responsive while sending structured data updates to RESTful APIs.
π Key Takeaways:
- PUT is used to update existing data (vs. POST for create)
- Requires a specific URL endpoint and JSON payload
- Prefer
fetch()
for cleaner, promise-based syntax - Always set the correct headers and handle responses
βοΈ Next Steps:
- Build a CRUD app that uses PUT for updating entries
- Explore PATCH for partial updates
- Learn how to handle CORS and authorization headers with PUT
β FAQs β AJAX PUT Request
β When should I use PUT instead of POST?
β
Use PUT when you want to update an existing record. Use POST when creating a new one.
β Can I use PUT with FormData?
β
Technically yes, but PUT is commonly used with JSON payloads. Use POST
or PATCH
for FormData operations.
β Is PUT idempotent?
β
Yes. Sending the same PUT request multiple times will not create duplicate recordsβit will overwrite the same resource.
β Do I need to set headers for PUT?
β
Yes. Use Content-Type: application/json
when sending JSON data.
β What status code indicates a successful PUT?
β
Usually 200 OK
or 204 No Content
if no data is returned from the server.
Share Now :