0
votes

I am trying to post using ajax in laravel 5. I get CSRF token mismatch exception. I have looked around and found may such issues, but in this case I did include all the code necessary.

Please take a look at my code.

View

{!! Form::open(array('url'=>'admin/index','method'=>'POST', 'id'=>'addrole')) !!}
<div class="control-group">
  <div class="controls">
     {!! Form::text('user','',array('id'=>'','class'=>'form-control span6','placeholder' => 'Username')) !!}
  </div>
</div>
<div class="control-group">
  <div class="controls">
      {!! Form::text('role','faculty',array('class'=>'form-control span6', 'placeholder' => 'User Role')) !!}
      <input type="hidden" name="_token" value="{{ csrf_token()}}">
  </div>
</div>
{!! Form::button('Submit', array('class'=>'send-btn')) !!}
{!! Form::close() !!}

<script type="text/javascript">

    $.ajaxSetup({
       headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
    });

    $(document).ready(function(){
        $('.send-btn').click(function(){
            $.ajax({
                url: 'index',
                type: "post",
                data: {
                    '_token': $('input[name="_token"]').val(),
                    'user':$('input[name=user]').val(),
                    'role':$('input[name=role]').val()
                }, //, '_token': $('input[name=_token]').val()
                success: function(data) {
                    alert(data);
                }
            });
        });
    });
</script>

I have provided the token in hidden input and I include this in my post.

I do have a meta in head as follows.

<meta name="_token" content="{!! csrf_token() !!}"/>

The following is my controller.

public function index()
{
    if(Request::ajax()) {
        $data = Input::all();
        print_r($data);die;
    }
}

This one is just for testing, nothing much here. My routes are as follows

Route::get('admin/index', function() {
  return View::make('admin');
});
Route::post('admin/index', 'AdminController@index');

Please help me resolve this issue

this is the output in logs.

[2015-11-12 09:04:31] local.ERROR: exception 'Illuminate\Session\TokenMismatchException' in /var/www/html/vidman-laravel/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php:46
Stack trace:
#0 /var/www/html/vidman-laravel/app/Http/Middleware/VerifyCsrfToken.php(17): Illuminate\Foundation\Http\Middleware\VerifyCsrfToken->handle(Object(Illuminate\Http\Request), Object(Closure))
#1 /var/www/html/vidman-laravel/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(125): App\Http\Middleware\VerifyCsrfToken->handle(Object(Illuminate\Http\Request), Object(Closure))
#2 /var/www/html/vidman-laravel/vendor/laravel/framework/src/Illuminate/View/Middleware/ShareErrorsFromSession.php(55): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#3 /var/www/html/vidman-laravel/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(125): Illuminate\View\Middleware\ShareErrorsFromSession->handle(Object(Illuminate\Http\Request), Object(Closure))
#4 /var/www/html/vidman-laravel/vendor/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php(61): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#5 /var/www/html/vidman-laravel/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(125): Illuminate\Session\Middleware\StartSession->handle(Object(Illuminate\Http\Request), Object(Closure))
#6 /var/www/html/vidman-laravel/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/AddQueuedCookiesToResponse.php(36): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#7 /var/www/html/vidman-laravel/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(125): Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse->handle(Object(Illuminate\Http\Request), Object(Closure))
#8 /var/www/html/vidman-laravel/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/EncryptCookies.php(40): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#9 /var/www/html/vidman-laravel/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(125): Illuminate\Cookie\Middleware\EncryptCookies->handle(Object(Illuminate\Http\Request), Object(Closure))
#10 /var/www/html/vidman-laravel/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/CheckForMaintenanceMode.php(42): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#11 /var/www/html/vidman-laravel/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(125): Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode->handle(Object(Illuminate\Http\Request), Object(Closure))
#12 [internal function]: Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#13 /var/www/html/vidman-laravel/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(101): call_user_func(Object(Closure), Object(Illuminate\Http\Request))
#14 /var/www/html/vidman-laravel/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(115): Illuminate\Pipeline\Pipeline->then(Object(Closure))
#15 /var/www/html/vidman-laravel/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(84): Illuminate\Foundation\Http\Kernel->sendRequestThroughRouter(Object(Illuminate\Http\Request))
#16 /var/www/html/vidman-laravel/public/index.php(53): Illuminate\Foundation\Http\Kernel->handle(Object(Illuminate\Http\Request))
#17 {main} 

The following is my browser console post header and the in-page csrf token don't match. Please look below

The token in the page ==> input type="text" name="_token" value="{{ csrf_token()}}"

Browser post header

1
Can you see the token rendered in your html?Jerodev
yes infact i can. It is a token. I changed the hidden to text and can see a token. I am including the error also.RKV
'_token': $('input[name="_token"]').val() - you don't need that line, because you have already setup the header. Because you have setup that line, your post variables are being checked. And you don't have 'value' attribute in the element. You have 'content'. But that is not important. If you don't have a _token in the post data, Laravel will check the header, and you have already set it up. So just delete this line and try again.naneri
I tried that too. It does'nt work.RKV
I just noticed that my CSRF value in the page (input tag) doesn't change on refresh. I though it changes for every refresh of the pageRKV

1 Answers

1
votes

I think when you use

{!!  Form::open() !!}

this already include the csrf_token in your form input tag.So, it is not necessary to include in meta tag or in input tag. For example: When you do this like:

{!! Form::open() !!}
{!! Form::close() !!}

Your form tag will be like :

<form action="your action" method="POST" accept-charset="UTF-8">
     <input type="hidden" value="token_string" name="_token" > 
</form>

Now in your js file to verfiy the token you can do like this :

$.ajaxSetup({
    headers:{
        'X-CSRF-Token' : $("input[name='_token'").attr('value')
    }
});