8

I am trying to use Jquery.ajax() with PUT and DELETE methods and sending some data along with the request but in the php side when printing the request it comes empty.

$.ajax({
url: 'ajax.php',
type: 'DELETE',
data: {some:'some',data:'data'},
}

In PHP:

print_r($_REQUEST);

and I get an empty array. I don't know if it is a jquery or php thing or simply I can't send data that way. I know DELETE method is meant to be used without sending additional data but here every ajax request is sent to the same script.

olanod
  • 30,306
  • 7
  • 46
  • 75
  • possible duplicate of [How to get body of a POST in php?](http://stackoverflow.com/questions/8945879/how-to-get-body-of-a-post-in-php/8945912#8945912) –  Feb 03 '12 at 15:17
  • I just want to feel fancy and sofisticated using all methods. if not possible i'll stick to POST – olanod Feb 03 '12 at 15:18

3 Answers3

18

To retrieve the contents of the HTTP request body from a PUT request in PHP you can't use a superglobal like $_POST or $_GET or $_REQUEST because ...

No PHP superglobal exists for PUT or DELETE request data

Instead, you need to manually retrieve the request body from STDIN or use the php://input stream.

$_put = file_get_contents('php://input');

The $_GET superglobal will still be populated in the event of a PUT or DELETE request. If you need to access those values, you can do it in the normal fashion. I'm not familiar with how jquery sends along the variables with a DELETE request, so if $_GET isn't populated you can instead try manually parsing the $_SERVER['QUERY_STRING'] variable or using a custom "action" parameter as suggested by @ShankarSangoli to accommodate outdated browsers who can't use javascript to send a DELETE request in the first place.

  • 1
    Tanks I didnt know that, here is how I get the request array: function getRequest(){ $query_str = file_get_contents("php://input"); $array = array(); parse_str($query_str,$array); return $array;} – olanod Feb 03 '12 at 16:04
4

I think DELETE type is not support by all the browser. I would pass an addtional parameter say action: delete. Try this.

$.ajax({
  url: 'ajax.php',
  type: 'POST',
  data: {  some:'some', data:'data', action: 'delete' },
}
ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124
  • 1
    I actually do it that way and works as expected, I was just looking the RESTful way to do it ;) – olanod Feb 03 '12 at 15:28
  • The most common way I see this done with RESTful API is `_method=delete`. I expect more developers would be familiar with that. – abraham Feb 03 '12 at 18:37
3

It might be an browser issue as said in the jQuery documentation:

The type of request to make ("POST" or "GET"), 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.

http://api.jquery.com/jQuery.ajax/

DerDee
  • 392
  • 2
  • 10