How to send a PUT/DELETE/HEAD/PATCH request in jQuery?

September 19, 2022 No comments put delete request jquery javascript

1. Introduction

In jQuery a method .get() and .post() may be used to make GET and POST HTTP requests, however the .put(), .delete() or .patch() methods are not supported. In this article, we'll look at how to prepare other than POST and GET HTTP requests using jQuery.

2. Using jQuery .ajax() method to make PUT/DELETE/HEAD/PATCH request

The .ajax() function in jQuery could be use to send all kind of HTTP requests. This method allows us to define the type of request.

The type attribute is an HTTP method to use for the request (e.g. "POST", "GET", "PUT").

For HTTP DELETE use:

$.ajax({
    url: '/posts/123456',
    type: 'DELETE',
    success: function(result) {
        // Do something with the result
    }
});

For HTTP PUT use:

$.ajax({
   url: '/posts/123456',
   type: 'PUT',
   data: { } // some data here
   success: function(response) {
     //...
   }
});

3. Extending jQuery to handle differently than GET/POST HTTP methods

We can extend jQuery with dedicated methods for different HTTP types:

jQuery.each(["put", "delete", "head", "patch"], function(i, method) {
  jQuery[method] = function(url, data, callback, type) {
    if (jQuery.isFunction(data)) {
      type = type || callback;
      callback = data;
      data = undefined;
    }

    return jQuery.ajax({
      url: url,
      type: method,
      dataType: type,
      data: data,
      success: callback
    });
  };
});

And use them as follows:

$.put("http://example.com/posts/123456789", {
  title: "test"
}, function(result) {
  console.log(result);
});

$.path("http://example.com/posts/123456789", {
  title: "test"
}, function(result) {
  console.log(result);
});

4. Conclusion

In this article, we presented a method to send a PUT/DELETE/HEAD/PATCH requests using jQuery.

{{ message }}

{{ 'Comments are closed.' | trans }}