Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PUT, DELETE data from Jquery to PHP

Tags:

rest

jquery

php

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.

like image 797
olanod Avatar asked Feb 03 '12 15:02

olanod


People also ask

How to DELETE data using jQuery in PHP?

php', data:del_id, success: function(data){ if(data=="YES"){ $ele. fadeOut(). remove(); }else{ alert("can't delete the row") } } }) }) });

How to send a PUT DELETE request in jQuery?

Approach: To make a PUT or DELETE requests in jQuery we can use the . ajax() method itself. We can specify the type of request to be put or delete according to the requirement as given in the example below.

Does AJAX support Delete method?

The ajax() function is used to perform an asynchronous HTTP request to the server and by using the delete value for the type option it describes to the server that the specific data is to be deleted.


2 Answers

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.

like image 60
rdlowrey Avatar answered Sep 23 '22 21:09

rdlowrey


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' },
}
like image 40
ShankarSangoli Avatar answered Sep 21 '22 21:09

ShankarSangoli