Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ChiefJS's avatar

AJAX post request: TokenMismatchException

I'm running into a TokenMismatchmatchException error when I try to submit a form. What could be causing this? The code in my view:

<form class="form" id="form-add">
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
    @foreach($members as $member)
    <div class="form-group col-md-3" style="display: none;">
        <input type="text" name="user_id" class="form-control" value="{{ $member->user_id }}">

    </div>
    @endforeach

    <div class="form-group col-md-5">
        <label for="cartype">Car Type</label>
        <select name="cartype" id="cartype" class="form-control">
            <option>Choose a car type</option>
            @foreach($types as $type)
            <option value="{{ $type->cartypeid }}">{{ $type->car_type }}</option>

            @endforeach

        </select>

    </div>
    <div class="form-group col-md-5">
        <label for="model">Model</label>
        <select name="model" id="model" class="form-control">
            <option value=""></option>

        </select>

    </div>
    <div class="form-group col-md-2">
        <button type="submit" class="btn add-btn btn-primary">Add</button>

    </div>

</form>

The javascript

$('#cartype').on('change', function(e){
    console.log(e);
    var car_id = e.target.value;
    $.get('/ajax-model?modid=' + car_id, function (data) {
        $('#model').empty();
        $.each(data, function (index, accssObj) {
            $('#model').append('<option value="' + modObj.modelid + '">' + modObj.model + '</option>');
        })
    })

});
$(function(){
    $('#form-add').submit(function(e){
        e.preventDefault();
        var _token = $('input[name="_token"]').val();
        var user_id = $('input[name="user_id"]').val();
        var model = $('input[name="model"]').val();

        var data = new FormData();
        data.append('_token', _token);
        data.append('user_id', user_id);
        data.append('model', model);

        $.ajax({
            url: '/save',
            type: 'POST',
            data:data,
            dataType: "json",
            processData: false,
            success:function(data){
                alert('Item added!');
            },
            error:function(data){
                alert('Failed!');
            }
        });

    });
});

And the controller

public function save(Request $request)
{
    $validator = Validator::make($request->all(), [
        'user_id' => 'required'
    ]);

    if($validator->fails()){
        return redirect()->back()
            ->withErrors($validator)
            ->withInput();
    }

    $cmodel = new CarModel();

    $cmodel->user_id = $request->input('user_id');
    $cmodel->model_id = $request->input('access');
    $cmodel->created_by = Auth::user()->username;
    $cmodel->status = 0;

    $cmodel->save();

    Session::flash('flash_message', 'The item has been added.');

    return redirect()->back();
}
                    
0 likes
10 replies
ChiefJS's avatar

@SachinAgarwal I have changed the javascript to this

$(function(){
                $('#form-add').submit(function(e){
                    e.preventDefault();
                    var data  = $('#form-add').serializeArray();

                    $.ajax({
                        url: '/save',
                        type: 'POST',
                        data:data,
                        dataType: "json",
                        processData: false
                    });

                });
            });

And in the head tag added

<meta name="csrf-token" content="{{ csrf_token() }}">

But I'm still getting the same error. And when I inspect what is being posted, all I can see is [object Object],[object Object],[object Object],[object Object]

Pendo's avatar

Just read the URLs we provided.. is it really that hard? You still have to add it to your Ajax call:

$.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
});
1 like
ChiefJS's avatar

@Pendo I'm no longer getting the error but nothing is being saved in the database

Pendo's avatar

Do you have the correct route (by default it's /create for a restful route) and does the ajax request in your console look correct?

You can perhaps add some debugging to your save() method (dump-and-die: dd()) to see what happens in the method. Since Flash only works after refreshing the page.

ChiefJS's avatar

@Pendo This is what I have in the routes file

Route::post('/save', 'CarController@save');

The code was working quite fine until I decided to use AJAX

ChiefJS's avatar

@Pendo When I place var_dump() before save(), I'm not getting the data being posted

Pendo's avatar

Well, to see the data you should at least dump the vars:

var_dump( Request::all() );

Don't forget to

use Request;

on top of your document

SachinAgarwal's avatar

@ChiefJS Probably You will have to do JsonDecode on the post data you are receiving. But I think laravel already does it for you.

Please or to participate in this conversation.