Ashok Lama
Ashok Lama

Reputation: 48

TokenMismatchException in Laravel 5.0

I have a form inside a div.

<div class="form-container col-sm-12 container-fluid">
<meta content="{{ csrf_token() }}" name="_token">
<form class="form" id="register_form" method="POST" novalidate>
    <!-- <input type="hidden" value="{{ csrf_token() }}" name="_token" id="token"> -->
    <div class="form-group" id="error_msg"></div>
    <div class="form-group name">                        
        <input type="text" class="form-control input-sm" role="group" id="name" placeholder="Name" name="name" required>                  
    </div>
    <div class="form-group email"> 
        <input type="email" class="form-control input-sm" id="email" placeholder="Email" name="email" required>      
    </div>
    <div class="form-group contact_no">
        <input type="text" class="form-control input-sm" id="contact_no" placeholder="Contact No" name="contact_no" required>
    </div>
    <div class="form-group select_level">
        <select class="form-control input-sm" name="level_interested" id="level_interested" required>
            <option class="form-control" selected disabled value="">Level Interested</option>
            <option class="form-control" value="bachelor">Bachelor</option>
            <option class="form-control" value="masters">Masters</option>
            <option class="form-control" value="phd">Phd</option>
            <option class="form-control" value="nursing">Nursing</option>
        </select>
    </div>
    <div class="form-group select_country">
        <select class="form-control input-sm" name="country_interested" id="country_interested" required>
            <option class="form-control" selected disabled value="">Country Interested</option>
            <option class="form-control" value="usa">U.S.A</option>
            <option class="form-control" value="australia">Australia</option>
            <option class="form-control" value="canada">Canada</option>
            <option class="form-control" value="india">India</option>
            <option class="form-control" value="new_zealand">New Zealand</option>
        </select>
    </div>

    <div class="form-group">
        <button type="submit" class="btn btn-success btn-sm">Register</button>
    </div>
</form>    

When the form is submitted, validation is carried on. After successful validation, I use Ajax to send input data and display alert message in response.

form.submit(function() {
        if(validateName() & validateEmail() & validateContact_No() & validateLevel() & validateCountry()) {

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

            $.ajax({
                type : 'post',

            url: "{{ route('save_registry') }}",

            data: {
                'name' : name.val(),
                'email' : email.val(),
                'contact_no' : contact_no.val(),
                'level_interested' : level_interested.val(),
                'country_interested' : country_interested.val(),
            },

            success : function(data) {

                    alert(data);

            }
        });
            return true;
        } else {
            $('#error_msg').text("Please Enter Details Correctly").show().addClass('text-danger').addClass('text-center');
            return false;
        }

This is my function in a Controller to handle the request.

public function save_registry(Request $request)
{


    $new_registry = new Register();

    $email = Register::where('email','=',$request->email)->exists();
    if($email==true)
    {
        return 'Email already exists';
    }
    else{
        $new_registry -> name = $request -> name;
        $new_registry -> email = $request -> email;
        $new_registry -> contact_no = $request -> contact_no;
        $new_registry -> level_interested = $request -> level_interested;
        $new_registry -> country_interested = $request -> country_interested;
        $new_registry->save();
        return 'Registered Successfully';
    }
}

After I submit the form, alert is popped. And after I close the alert, I get TokenMismatchException error. I get this error only when the form's method is POST not in GET. So is there any solution to not to get the error when the method is POST?

Upvotes: 0

Views: 59

Answers (1)

Tim Lewis
Tim Lewis

Reputation: 29316

Laravel looks for an attribute called _token when you submit a form via POST. I see you already have this in a <meta> tag, so you have two methods to get this when you POST your form.

First, you can create a new <input type="hidden" name="_token" value="{{ csrf_token() }}"/> element somewhere in your <form>, and make sure that is passed via your ajax when the method is POST:

data: {
    '_token' : _token.val(),
    'name' : name.val(),
    'email' : email.val(),
    'contact_no' : contact_no.val(),
    'level_interested' : level_interested.val(),
    'country_interested' : country_interested.val(),
},

Alternatively, since you already have the conent in a <meta> tag, you can just include it in your ajax like so:

data: {
    '_token' : $('meta[name="_token"]').attr('content'),
    'name' : name.val(),
    'email' : email.val(),
    'contact_no' : contact_no.val(),
    'level_interested' : level_interested.val(),
    'country_interested' : country_interested.val(),
},

Regardless of how you do it, just make sure to have that _token attribute in your POST data, and it should work for you. Hope that helps!

Upvotes: 1

Related Questions