MedYasser.alkahf
MedYasser.alkahf

Reputation: 235

Laravel 5, ajax, 500 Internal Server Error, TokenMismatchException in VerifyCsrfToken.php line 46:

I'm using Laravel 5 with ajax post in a popup alert, and it giving me the error "500 Internal Server Error", when I checked firebug, I find that ajax return an error page saying "TokenMismatchException in VerifyCsrfToken.php line 46:"

when I comment App\Http\Middleware\VerifyCsrfToken, it works fine, but I assume that it's not recommended, I print the _token variable and it's not empty
the ajax post code is:

 $('#demo_4').click(function(){
        bootbox.prompt("What is your name?", function(result) {
            if (result === null) {
                alert("Prompt dismissed");
            } else {
                // alert("Hi <b>"+result+"</b>");
                $.ajax({
                    url: 'test',
                    type: "post",
                    data: {'name':result, '_token': $('input[name=_token]').val()},
                    success: function(data){
                        alert(data);
                    }
                });
            }
        });
    });

the Route code is:

Route::post('test', 'AccountController@login');

the AccountController code is:

<?php
namespace App\Http\Controllers;
use Input;
use Request;
use App\Http\Controllers;

class AccountController extends Controller 
{

    public function login()
    {

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

    }
}

Upvotes: 1

Views: 4722

Answers (2)

RAJESHINDIN
RAJESHINDIN

Reputation: 181

I have also faced similar problem

Replace data: {'name':result, '_token': $('input[name=_token]').val()}, with data: {'name':result, '_token': "$('input[name=_token]').val()"},

Placing double quotes around token solved my problem.

Upvotes: 0

Nikolaj Sarry
Nikolaj Sarry

Reputation: 243

You need to insert this line to your form

<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">

Or adding this to controller

use Illuminate\Support\Facades\Session

Please enable debugger and provide what Laravel5 debugger shows to speak more detail.

In ajax call add this to data option:

'_token':$('input[name=_token]').val()

Or in globally way add

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

And add to footer:

<script type="text/javascript">
    $.ajaxSetup({
        headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
    });
</script>

UPD: to controller

use Input;
use Request;
class AccountController extends Controller {
    public function login() 
    {
    // Getting all post data
    if(Request::ajax()) {
        $data = Input::all();
        print_r($data);die;
    }
}

UPD2: try to add this to your main layout

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

<script type="text/javascript">
    $.ajaxSetup({
        headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
    });
</script>

Check that your web server has already write access to session directory, it can be app/storage/framework/sessions/. Execute

rm -f {your_web_app}/storage/framework/sessions/*

Reload web server.

In some cases check app/Http/Middleware/VerifyCsrfToken.php for tokensMatch method with this code:

$token = $request->ajax() ? $request->header('X-CSRF-Token') : $request->input('_token');

return $request->session()->token() == $token;

And check javascript file for this:

// CSRF protection
$.ajaxSetup(
{
    headers:
    {
        'X-CSRF-Token': $('input[name="_token"]').val()
    }
});

Upvotes: 3

Related Questions