Reputation: 717
I'm trying to send some data via AJAX to my Laravel app.
I'm using jQuery for the AJAX bit.
The HTTP method
I am trying to do it with is PATCH
.
I want to include the method name (patch) in the data
and keep the type
as POST
, as this will ensure greater browser-compatibility.
I set everything up using PATCH
as the type
, and all was working fine.
Then I changed the type
to POST
and put the 'spoofed' method name in the data
. Then things stopped working.
Here is my current AJAX code:
var request = $.ajax({
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
url: ajaxURL,
type: "POST",
data: JSON.stringiy({_method: "PATCH", more_data:[the_data]}),
dataType: "json"
});
request.done(function( msg ) {
alert(JSON.stringify(msg));
});
Now, the above does work in the sense that it successfully runs. But Laravel does not recognise the spoofed method (and throws a MethodNotAllowed exception)... It does recognise the spoofed method
and all works, when I don't use JSON.stringify
on the data
, but I need to do it this way for everything to work.
I feel I am very close, and I just need to put some code, maybe a new middleware class and route these requests through it, so that I can successfully spoof the PATCH HTTP
method?
Any ideas?
Thanks!
Upvotes: 0
Views: 705
Reputation: 1835
Here is how to Laravel check request method (vendor/Symfony/http-foundation/Request.php
)
public function getMethod()
{
if (null === $this->method) {
$this->method = strtoupper($this->server->get('REQUEST_METHOD', 'GET'));
if ('POST' === $this->method) {
if ($method = $this->headers->get('X-HTTP-METHOD-OVERRIDE')) {
$this->method = strtoupper($method);
} elseif (self::$httpMethodParameterOverride) {
$this->method = strtoupper($this->request->get('_method', $this->query->get('_method', 'POST')));
}
}
}
return $this->method;
}
As you can see you need send X-HTTP-METHOD-OVERRIDE
header for correct route handle. In your case you can just add
headers: { 'X-HTTP-Method-Override': 'PATCH' },
Upvotes: 1