ajax post in laravel 5 return error 500 (Internal

2019-01-11 11:02发布

this is my test ajax in laravel 5 (refer below)

$("#try").click(function(){
    var url = $(this).attr("data-link");
    $.ajax({
        url: "test",
        type:"POST",
        data: { testdata : 'testdatacontent' },
        success:function(data){
            alert(data);
        },error:function(){ 
            alert("error!!!!");
        }
    }); //end of ajax
});

and the trigger link

<a href="#" id="try" data-link="{{ url('/test') }}">Try</a>

and my route

Route::post('test', function()
{
    return 'Success! ajax in laravel 5';
});

but it gives me error when I run the console in google chrome and it doesnt return the expected response "return 'Success! ajax in laravel 5';"

POST http://juliver.laravel.com/test 500 (Internal Server Error)

whats wrong/problem to my code? anything im missing?

9条回答
迷人小祖宗
2楼-- · 2019-01-11 11:26

You can add your URLs to VerifyCsrfToken.php middleware. The URLs will be excluded from CSRF verification.

protected $except = [
    "your url",
    "your url/abc"
];
查看更多
\"骚年 ilove
3楼-- · 2019-01-11 11:29

you have to pass the csrf field through ajax please look at the code here

$.ajax({
                                        type: "POST",
                                        url:'{{URL::to("/delete-specialist")}}',
                                        data: {
                                            id: id,

                                            _token: $('#signup-token').val()
                                        },
                                        datatype: 'html',
                                        success: function (response) {
                                            if(response=="deleted"){
                                                $("#"+id).hide();
                                                $("#message").html("successfully deleted");
                                            }

                                        }

                                    });

and you also need to write this input field before this

<input id="signup-token" name="_token" type="hidden" value="{{csrf_token()}}">

still if you do not understand please enjoy this video https://www.youtube.com/watch?v=ykXL8o0slJA&t=20s

查看更多
你好瞎i
4楼-- · 2019-01-11 11:30

By default Laravel comes with CSRF middleware.

You have 2 options:

  1. Send token in you request
  2. Disable CSRF middleware (not recomended): in app\Http\Kernel.php remove VerifyCsrfToken from $middleware array
查看更多
登录 后发表回答