Skip to main content

AJAX Send PUT Requests

AJAX - Send PUT Requests

Sending PUT Requests in AJAX allows you to update existing data on the server using the HTTP PUT method without reloading the entire webpage. This enables efficient and asynchronous communication between the client and server, facilitating various operations such as data modification, resource updates, and more.


1. Sending Data via PUT Request

To send data via a PUT request in AJAX, you can use the jQuery AJAX function or the native XMLHttpRequest object. Specify the URL, method, and data to be sent in the AJAX request.

Example using jQuery AJAX:

// Sending data via PUT request using jQuery AJAX
$.ajax({
  url: 'https://api.example.com/updateData/123',
  method: 'PUT',
  data: {
    name: 'John Doe',
    email: 'john@example.com'
  },
  success: function(response) {
    // Handle success response
    console.log('Data updated successfully:', response);
  },
  error: function(xhr, status, error) {
    // Handle errors
    console.error('Error:', status, error);
  }
});

In this example, we use jQuery's AJAX function to send a PUT request to the specified URL ('https://api.example.com/updateData/123') with the provided data (name and email).


2. Updating Resource Data

A common use case for sending PUT requests in AJAX is updating resource data on the server. You can modify existing data by specifying the resource identifier in the URL and sending the updated data in the request body.

Example:

// Updating resource data via PUT request
$.ajax({
  url: 'https://api.example.com/updateResource/123',
  method: 'PUT',
  data: {
    status: 'active',
    description: 'Updated resource description'
  },
  success: function(response) {
    // Handle success response
    console.log('Resource updated successfully:', response);
  },
  error: function(xhr, status, error) {
    // Handle errors
    console.error('Error:', status, error);
  }
});

In this example, we send a PUT request to update resource data identified by the ID '123'. The updated status and description are sent in the request body.


3. Conclusion

Sending PUT Requests in AJAX is a powerful method for updating existing data on the server in web applications. By utilizing AJAX to send PUT requests asynchronously, developers can implement efficient data modification workflows and enhance the user experience.

Comments