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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With