harunB10 harunB10 - 3 months ago 53
jQuery Question

VerifyCsrfToken Exception on form submit after AJAX response

I have AJAX action which renders a form which contains several input fields and submit button.

This is AJAX call:

<script type="text/javascript">

$('#call_filter').click(function() {
url : 'brandSpendingsFilter',
type: 'POST',

data: {company: $('#company').val(), country: $('#country').val(), dateFrom: $('#dateFrom').val(), dateUntil: $('#dateUntil').val(), media: $('#media').val(),
products: $('[id^=products_]').serialize()},

beforeSend: function() {$('#search_result').empty(); $("#loading-image2").show(); },
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
success : function(data) {


And my form:

{!! Form::open(['url' => 'brandSpendingsCSV', 'method' => 'POST', 'id' => 'csv']) !!}
{{ csrf_field() }}
<input type="hidden" name="campaignID" value="@foreach($campaignID as $c){{$c}},@endforeach">
<input type="hidden" name="dateFrom" value="{{$dateFrom}}">
<input type="hidden" name="dateUntil" value="{{$dateUntil}}">
<input type="hidden" name="media" value="{{$media}}">
<input type="hidden" name="country" value="{{$country}}">


<div class="row" style="float: right;"><button type="submit" onclick="submitForm()" class="btn btn-warning">CSV EXPORT</button></div>


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

This onclick function is simple submit code:

<script type="text/javascript">
function submitForm(){

As you can see from the form code I have already included the csrf field. But still after this I am getting an error
Another thing that I have tried is to include AJAX headers:

<script type="text/javascript">

$(document).ready(function () {

headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')


But still error remains. Any suggestions?


I changed route type to GET and added this

<a href="brandSpendingsCSV?campaignID=@foreach($campaignID as $c){{$c}},@endforeach&dateFrom={{$dateFrom}}&dateUntil={{$dateUntil}}&media={{$media}}&country={{$country}}"><button class="btn btn-warning">CSV EXPORT</button></a>

It works at the moment, but I'll keep the question open since this is temporary solution. I need to have POST method.

Answer Source

You are creating token in page by usign {{ csrf_field() }}, so you can use as

 headers: {
   'X-CSRF-TOKEN': $('input[name="_token"]').val()

or add an element named _token to post data

var _token = $('input[name="_token"]').val();
data: {_token:_token,company: $('#company').val(),

Also calculate value campaignID before textbox or at the top of page

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download