As far as I know, the CSRF token should be in the headers for an ajax request, see here:
https://laravel.com/docs/master/routing#csrf-x-csrf-token http://engageinteractive.co.uk/blog/csrf-protection-with-ajax-and-laravel
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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();
}
Please or to participate in this conversation.