Ajax post request in laravel 5 return error 500 (Internal Server Error)
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.
90% of the laravel ajax internal server error is due to missing CSRF token. other reasons can inlucde:
- Wrong Request Type (e.g sending post to get)
- Wrong data type recived (e.g ajax is expecting JSON and app returns string)
- Your .htaccess is misconfigured
- Missing Route
- Code Error
You can read further about this in details here: https://abbasharoon.me/how-to-fix-laravel-ajax-500-internal-server-error/
I guess this has been solved by now but still the best thing to do here is to send the token with your form
{!! csrf_field() !!}
and then in your ajax
$("#try").click(function(){
var url = $(this).attr("data-link");
$.ajax({
url: "test",
type:"POST",
data: { '_token': token, 'someOtherData': someOtherData },
success:function(data){
alert(data);
},error:function(){
alert("error!!!!");
}
}); //end of ajax
});
You can add your URLs to VerifyCsrfToken.php middleware. The URLs will be excluded from CSRF verification.
protected $except = [
"your url",
"your url/abc"
];
In App\Http\Middleware\VerifyCsrfToken.php you could try updating the file to something like:
class VerifyCsrfToken extends BaseVerifier {
private $openRoutes =
[
...excluded routes
];
public function handle($request, Closure $next)
{
foreach($this->openRoutes as $route)
{
if ($request->is($route))
{
return $next($request);
}
}
return parent::handle($request, $next);
}
};
This allows you to explicitly bypass specific routes that you do not want verified without disabling csrf validation globally.