i'm using resource group and use this filter to resolve TokenMismatchException
problem:
Route::filter('csrf', function($route, $request) { if (strtoupper($request -> getMethod()) === 'GET') { return; // get requests are not CSRF protected } $token = $request -> ajax() ? $request -> header('X-CSRF-Token') : Input::get('_token'); if (Session::token() != $token) { throw new Illuminate\Session\TokenMismatchException; } });
my route :
Route::group(array('prefix'=> 'admin', 'before' => 'csrf'), function(){ Route::resource('profile' , 'ProfileController', array('as'=>'profile') ); });
now. i get error to Ajax requests such as this code:
<script type="text/javascript"> $(document).ready(function() { $('#frm').submit(function(e){ e.preventDefault(); name = $('#name').val(); family = $('#family').val(); email = $('#email').val(); currPassword = $('#currPassword').val(); password = $('#password').val(); password_confirmation = $('#password_confirmation').val(); $.post("{{ route('admin.profile.update', $profile->id) }}", { _method : 'PUT', name : name, family : family, email : email, currPassword : currPassword, password : password, password_confirmation : password_confirmation }, function(data) { alert(data.errors.name); },'json'); return false; }); }); </script>
ERROR:
{"error":{"type":"Illuminate\\Session\\TokenMismatchException","message":"","file":"\/var\/www\/alachiq\/app\/filters.php","line":83}}
i think i'm must be sent _token in $.post
. but i can not get input
tag with name
attribute. iget this error:
TypeError: 'stepUp' called on an object that does not implement interface HTMLInputElement.
ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]'). attr('content') } }); Hope this is helpful!
There is a tip in the Laravel docs on how to do this. This might not have been available at the time of the question, but I thought I would update it with a answer.
http://laravel.com/docs/master/routing#csrf-x-csrf-token
I have tested the meta tag method from the documentation and got it working. Add the following meta tag into your global template
<meta name="csrf-token" content="{{ csrf_token() }}">
Add this JavaScript that sets defaults for all ajax request in jQuery. Preferably in a js file that is included across your app.
$.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } })
This token can exist in the request header or the form. This populates it into the request header of every ajax request.
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