Programster's Blog

Tutorials focusing on Linux, programming, and open-source

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);

Be sure to set the request header after you open the request.

References

Last updated: 8th August 2020
First published: 7th August 2020