πŸ” AJAX Request & Response Lifecycle
Estimated reading: 4 minutes 35 views

πŸ”„ 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 and fetch()
  • 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?

FeaturePOSTPUT
ActionCreate a new resourceUpdate an existing resource
TargetOften generic (/users)Specific (/users/123)
Idempotent❌ No (multiple calls = multiple entries)βœ… Yes (multiple calls = same result)
Use CaseUser registrationUser 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 updatesUse PUT for full updates, PATCH for partial ones
Sending raw objectsAlways use JSON.stringify() to serialize payload
Forgetting content-type headerSet Content-Type: application/json
Ignoring server errorsAlways 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 :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

AJAX – Send PUT Request

Or Copy Link

CONTENTS
Scroll to Top