In this tutorial you will learn about the Laravel 5 Fix Ajax Post 500 Internal Server Error and its application with practical example.
Laravel 5 Fix Ajax Post 500 Internal Server Error
Many times while trying to submit form data using ajax you encounter 500 internal server error, in most of the cases this happens due to not adding csrf_token with form data or not setting X-CSRF-TOKEN request header with ajax form submit request. In this tutorial, I’ll show you how to add CSRF Meta and Ajax Headers properly to avoid internal server error.
Add CSRF Meta and Set Ajax Headers
Laravel comes with a security mechanism called csrf token. In Laravel, each of the request is attached a csrf_token that is validated before can be processed. In order to submit form data using ajax, we must have to incorporate csrf token with form data and set X-CSRF-TOKEN request header with ajax form submit request. This CSRF Token can generated using csrf_token() helper of laravel 5.
Add CSRF Token In Meta tag :-
1 |
<meta name="csrf-token" content="{{ csrf_token() }}"> |
Set CSRF Token In jQuery Ajax Header :-
1 2 3 4 5 |
$.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); |