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.

2
  • possible duplicate of How to get body of a POST in php? Commented Feb 3, 2012 at 15:17
  • I just want to feel fancy and sofisticated using all methods. if not possible i'll stick to POST Commented Feb 3, 2012 at 15:18

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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;}
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' },
}

2 Comments

I actually do it that way and works as expected, I was just looking the RESTful way to do it ;)
The most common way I see this done with RESTful API is _method=delete. I expect more developers would be familiar with that.
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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.