Laravel - check if Ajax request

后端 未结 11 795
梦谈多话
梦谈多话 2020-12-08 00:09

I have been trying to find a way to determine ajax call in Laravel but i don\'t find any document regarding it.

I have a index() function which i want t

相关标签:
11条回答
  • 2020-12-08 00:12

    $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
    
    0 讨论(0)
  • 2020-12-08 00:13

    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)

    0 讨论(0)
  • 2020-12-08 00:15

    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';}
    });
    
    0 讨论(0)
  • 2020-12-08 00:20

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

    0 讨论(0)
  • 2020-12-08 00:22

    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";
            }
    
    0 讨论(0)
  • 2020-12-08 00:24

    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.

    0 讨论(0)
提交回复
热议问题