Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - check if Ajax request

Tags:

php

laravel

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.

like image 871
Raheel Avatar asked Oct 15 '22 04:10

Raheel


People also ask

How to check if ajax is working in Laravel?

In Laravel, we can use $request->ajax() method to check request is ajax or not.

How do I know if Ajax is working?

ajax() : $. ajax({ type: 'POST', url: 'page. php', data: stuff, success: function( data ) { }, error: function(xhr, status, error) { // check status && error }, dataType: 'text' });


1 Answers

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";
        }
like image 229
Crack_David Avatar answered Oct 17 '22 18:10

Crack_David