128

I have been trying to find a way to determine Ajax calls in Laravel but I have not found any documentation about it.

I have an index() controller function where I want to handle the response differently based on the nature of the request. Basically this is a resource controller method that is bound to GET request.

public function index()
{
    if(!$this->isLogin())
        return Redirect::to('login');
            
    if(isAjax()) // This is what I am needing.
    {
        return $JSON;
    }

    $data = array(
        'records' => $this->table->fetchAll()
    );

    $this->setLayout(compact('data'));
}

I know the other methods of determining the Ajax request in PHP but I want something specific to Laravel.

Thanks

Updated:

I tried using

if(Request::ajax())
{
    echo 'Ajax';
}

But I am receiving this error:

Non-static method Illuminate\Http\Request::ajax() should not be called statically, assuming $this from incompatible context

The class shows that this is not a static method.

John Kary
  • 6,703
  • 1
  • 24
  • 24
Raheel
  • 8,716
  • 9
  • 60
  • 102

12 Answers12

243

Maybe this helps. You have to refer the @param

         /**       
         * Display a listing of the resource.
         *
         * @param  Illuminate\Http\Request $request
         * @return Response
         */
        public function index(Request $request)
        {
            if($request->ajax()){
                return "AJAX";
            }
            return "HTTP";
        }
Crack_David
  • 2,775
  • 1
  • 14
  • 30
31

$request->wantsJson()

You can try $request->wantsJson() if $request->ajax() does not work

$request->ajax() works if your JavaScript library sets an X-Requested-With HTTP header.

By default Laravel set this header in js/bootstrap.js

window.axios = require('axios');

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

In my case, I used a different frontend code and I had to put this header manually for $request->ajax() to work.

But $request->wantsJson() will check the axios query without the need for a header X-Requested-With:

// Determine if the current request is asking for JSON. This checks Content-Type equals application/json.
$request->wantsJson()
// or 
\Request::wantsJson() // not \Illuminate\Http\Request
  • Use `$request->wantsJson()` if your controller is deciding whether to respond with JSON or something else. This is a better approach than using `$request->isAjax()` because `wantsJson()` follows the HTTP spec for [Content Negotiation](https://developer.mozilla.org/en-US/docs/Web/HTTP/Content_negotiation). – John Kary Sep 08 '21 at 00:55
24

You are using the wrong Request class. If you want to use the Facade like: Request::ajax() you have to import this class:

use Illuminate\Support\Facades\Request;

And not Illumiante\Http\Request


Another solution would be injecting an instance of the real request class:

public function index(Request $request){
    if($request->ajax()){
        return "AJAX";
    }

(Now here you have to import Illuminate\Http\Request)

lukasgeiter
  • 147,337
  • 26
  • 332
  • 270
  • you are right. I fixed that. Some other guy put a use statement above and i didn't look at that. Thanks :) – Raheel Mar 24 '15 at 11:57
23

To check an ajax request you can use if (Request::ajax())

Note: If you are using laravel 5, then in the controller replace

use Illuminate\Http\Request;

with

use Request; 

I hope it'll work.

Jnanaranjan
  • 1,304
  • 15
  • 31
11
if(Request::ajax()) 

Looks to be the right answer. http://laravel.com/api/5.0/Illuminate/Http/Request.html#method_ajax

Matthew Way
  • 331
  • 1
  • 4
  • 1
    I am not sure if this is what you mean, but Laravel makes use of the Facade design pattern so that your calls can be made like static methods: http://laravel.com/docs/4.2/facades#facade-class-reference That link shows a list of Facades Laravel uses. Are you using it in a Controller? – Matthew Way Mar 24 '15 at 11:56
  • i was using wrong use statement. sorry But thanks for an overview of Facades :) This is informative. – Raheel Mar 24 '15 at 12:00
8

For those working with AngularJS front-end, it does not use the Ajax header laravel is expecting. (Read more)

Use Request::wantsJson() for AngularJS:

if(Request::wantsJson()) { 
    // Client wants JSON returned 
}
Community
  • 1
  • 1
Justin
  • 26,443
  • 16
  • 111
  • 128
7

Those who prefer to use laravel helpers they can check if a request is ajax using laravel request() helper.

if(request()->ajax())
   // code
lee shin
  • 894
  • 11
  • 6
4
public function index()
{
    if(!$this->isLogin())
        return Redirect::to('login');

    if(Request::ajax()) // This is check ajax request
    {
      return $JSON;
    }

    $data = array();
    $data['records'] = $this->table->fetchAll();

    $this->setLayout(compact('data'));
}
3

Sometimes Request::ajax() doesn't work, then use \Request::ajax()

Nagibaba
  • 4,218
  • 1
  • 35
  • 43
1
Do something like this
public function functionName(User $user): string
{
    (string) $message = "";
    // check if request is ajax
    if(request()->ajax())
    {
        if($this->isOwner($user->id)){
            $message = 'success';
        }else{
            $message = "You are unauthorized to perform this action.";
        }
    }else{
        $message = 'Wrong server request';
    }
    return $message;        
}
Pius T.K
  • 351
  • 5
  • 9
0

after writing the jquery code perform this validation in your route or in controller.

$.ajax({
url: "/id/edit",
data:
name:name,
method:'get',
success:function(data){
  console.log(data);}
});

Route::get('/', function(){
if(Request::ajax()){
  return 'it's ajax request';}
});
Gatogordo
  • 2,629
  • 2
  • 22
  • 32
-1

Most of the answers are working fine. We can also check the request header

request()->header('Accept')=='application/json'

to check the request type

Rahul Reghunath
  • 1,210
  • 13
  • 23