Fix Laravel Not Recognizing Ajax Requests
The Problem
Quite often you will have an URL endpoint that you want to respond with a normal plain http web response, except if the request came in as an ajax request, in which case you may wish to respond with a JSON response.
Laravel comes with the methods ajax()
and isXmlHttpRequest()
on the request object in order to determine if a request was an ajax request.
For example:
if ($request->ajax() || $request->isXmlHttpRequest())
{
$response = response()->json($asset);
}
else
{
$response = redirect("/assets/edit/" . $asset->id);
}
return $response;
Unfortunately, this wasn't working for me.
It turns out this is because Laravel is assuming that you are using JQuery, which will automatically set a specific header with a specific value when sending an ajax request. If you are a fan of using plain Javascript like me (you don't need JQuery), then this won't work for you. Laravel will return as if it was not an ajax request.
The Solution
Add the header named X-Requested-With
with value XMLHttpRequest
to your ajax request.
e.g.
var xhr = new XMLHttpRequest();
xhr.open("POST", "/assets/update");
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.send(formData);
open
the request.
References
First published: 7th August 2020