`$request->ajax()` does not detect ajax request when using Fetch API to pull data in Laravel

Viewed 1004

In my Laravel app, I am using Fetch API to load data on scroll. Below is my JS code in blade file

let route = '{{ route("load") }}' + '?q=' + encodeURI('{{ $para }}');
fetch(route)
.then(response => {
   if(!response.ok) {
       throw new Error('Network response was not ok');
   }
   return response.text();
})
.then(data => {                       
   console.log(data);                       
})
.catch((error) => {
   console.error('Error:', error);
})

And in my controller

public function loadData( Request $request )
{
    if( $request->ajax() ) {

       return $request->query('q');

     }
     return 'Not Ajax!';
}

It always return 'Not Ajax!';

I am not sure why this is happening. It was not a problem with other libraries like jQuery or Axios

3 Answers

Request::ajax() checks for the existance of the X-Requested-With header.

Since you're using fetch, you have to manually add this header to the options object:

fetch(route, {
  headers: {
    'X-Requested-With': 'XMLHttpRequest'
  },
})

Axios, for example, uses this by default due to how the bootstrap.js file is set up. jQuery adds it automatically for every request but cross-domain requests.

Please try to use request()->ajax() function instead of $request->ajax(). I think the problem is you have imported the wrong Request at the top. It happens with me also because of Editor

Be careful when using "return" in your methods. Try enclosing return 'Not Ajax!'; in else

else{
    return 'Not Ajax!';
}
Related