63

It seems that using jQuery Ajax POST will pass parameters, but PUT will not. I looked at the current jQuery code and PUT and DELETE are not there. I looked at 1.4.2 jQuery and PUT and DELETE are there.

What is the workaround for passing parameters with a PUT request using the current version of jQuery?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
andrei g
  • 797
  • 2
  • 8
  • 12

4 Answers4

95

Can you provide an example, because put should work fine as well?

Documentation -

The type of request to make ("POST" or "GET"); the default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.

Have the example in fiddle and the form parameters are passed fine (as it is put it will not be appended to url) -

$.ajax({
  url: '/echo/html/',
  type: 'PUT',
  data: "name=John&location=Boston",
  success: function(data) {
    alert('Load was performed.');
  }
});

Demo tested from jQuery 1.3.2 onwards on Chrome.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jayendra
  • 52,349
  • 4
  • 80
  • 90
36

You can use the PUT method and pass data that will be included in the body of the request:

let data = {"key":"value"}

$.ajax({
    type: 'PUT',
    url: 'http://example.com/api',
    contentType: 'application/json',
    data: JSON.stringify(data), // access in body
}).done(function () {
    console.log('SUCCESS');
}).fail(function (msg) {
    console.log('FAIL');
}).always(function (msg) {
    console.log('ALWAYS');
});
ow3n
  • 5,974
  • 4
  • 53
  • 51
  • The line with the comment `// access in body` - how can that data be accessed? In PHP when I try this and do some echoing both the $_GET and $_POST superglobals are empty arrays. – knot22 Sep 08 '19 at 23:50
  • 1
    It seems that adding `$data = json_decode(file_get_contents('php://input'), true);` to the PHP script allows the data to be accessed. – knot22 Sep 09 '19 at 00:05
  • 1
    NOTE: jQuery 1.9+ added `method` which is used instead of `type` so if you're coming here wondering why the docs aren't working, you might be running an older version of jQuery. – Joshua Pinter Mar 31 '20 at 20:14
11

For others who wind up here like I did, you can use AJAX to do a PUT with parameters, but they are sent as the body, not as query strings.

Dan Mandle
  • 5,608
  • 3
  • 23
  • 26
-9

Use:

$.ajax({
    url: 'feed/4', type: 'POST', data: "_METHOD=PUT&accessToken=63ce0fde", success: function(data) {
        console.log(data);
    }
});

Always remember to use _METHOD=PUT.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • I would generally advise against parsing the data as a string as this prevents the app been dynamic and is harder to read than a simple object array. Additionally you can use `type: 'PUT'` instead of putting it in the data. – Jono20201 Jul 07 '15 at 10:38