harunB10 harunB10 - 6 months ago 77
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() {
$.ajax({
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) {
$("#loading-image2").hide();
$('#search_result').append(data);
}
});
});

</script>


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}}">

</tr>
</table>
@if(Auth::user()->isAdmin())

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

<br>
<br>

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


This onclick function is simple submit code:

<script type="text/javascript">
function submitForm(){
$('#csv')[0].submit();
}
</script>


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

<script type="text/javascript">

$(document).ready(function () {

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

});
</script>


But still error remains. Any suggestions?

EDIT

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