Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
464 views
in Technique[技术] by (71.8m points)

php - Ajax post request in laravel 5 return error 500 (Internal Server Error)

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 an error when I run the console in google chrome and it doesn't 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 I'm missing?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

While this question exists for a while, but no accepted answer is given I'd like to point you towards the solution. Because you're sending with ajax, and presumably still use the CSRF middleware, you need to provide an additional header with your request.

Add a meta-tag to each page (or master layout): <meta name="csrf-token" content="{{ csrf_token() }}">

And add to your javascript-file (or section within the page):

$.ajaxSetup({
  headers: {
    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
  }
});

See https://laravel.com/docs/master/csrf#csrf-x-csrf-token for more details.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...