Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 964
Juliver Galleto Avatar asked May 10 '15 17:05

Juliver Galleto


1 Answers

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.

like image 125
Ben Fransen Avatar answered Oct 14 '22 20:10

Ben Fransen