How to make ajax request with anti-forgery token in mvc How to make ajax request with anti-forgery token in mvc ajax ajax

How to make ajax request with anti-forgery token in mvc


Rather than manually adding it to each request, I usually do something like this:

var token = $('input[name="__RequestVerificationToken"]').val();$.ajaxPrefilter(function (options, originalOptions) {  if (options.type.toUpperCase() == "POST") {    options.data = $.param($.extend(originalOptions.data, { __RequestVerificationToken: token }));  }});

This will automatically add your token to any ajax POST you do.


Have you added your token to the header of the ajax call?

You need to add AntiForgeryToken in your message header in the ajax call:

var token = $('input[name="__RequestVerificationToken"]').val();var headers = {};headers['__RequestVerificationToken'] = token;$.ajax({        url: ... some url,        headers: headers,        ....});

Try this in your code:

var token = $('input[name="__RequestVerificationToken"]').val();var tokenadr = $('form[action="/TransportJobAddress/Create"] input[name="__RequestVerificationToken"]').val(); var headers = {};var headersadr = {};headers['__RequestVerificationToken'] = token;headersadr['__RequestVerificationToken'] = tokenadr;$('#submitaddress').click(function subaddr(event) {    event.preventDefault();    event.stopPropagation();  //$('#addAddress').html('<img src="/img/animated-overlay.gif"> Sending...');   // $('#addAddress').blur();    //  $(this).bl    if ($('#Jobid').val()!="") {        $('#TransportJobId').val(parseInt($('#Jobid').val()));        $.ajax(              {                  url: '/TransportJobAddress/create',                  type: 'POST',                  headers:headersadr,                   data: "__RequestVerificationToken=" + token + "" + $('form[action="/TransportJobAddress/Create"]').serialize(),                  success: function poste(data, textStatus, jqXHR) { $('#addAddress').html(data); return false; },                  error: function err(jqXHR, textStatus, errorThrown) { alert('error at address :' + errorThrown); }              });    }    else {        var transportid = 2;        $.ajax({            url: '/TransportJob/create',            type: 'POST',            headers:headers,             data: $('form[action="/TransportJob/Create"]').serialize(),            success: function sfn(data, textStatus, jqXHR) {                transportid = parseInt(data);                $('#Jobid').val(data);               // alert('inserted id :' + data);                $('#TransportJobId').val((transportid));                $.ajax(         {             url: '/TransportJobAddress/create',             type: 'POST',             //beforeSend: function myintserver(xhr){               //        $('#addAddress').html('<div id="temp_load" style="text-align:center">please wait ...</div>');             //},             headers:headers,              data: $('form[action="/TransportJobAddress/Create"]').serialize(),             success: function poste(data, textStatus, jqXHR) {                 $('#addAddress').html(data);             },             error: function err(jqXHR, textStatus, errorThrown) {                 alert('error at address :' + errorThrown);             }         });            },            error: function myfunction(jqXHR, textStatus, errorThrown) {                alert("error at transport :" + jqXHR.textStatus);            },            complete: function completefunc() {              //  alert('ajax completed all requests');                return false;            }        });    }});

Added headers line in your ajax call.


Have you added the token to your View? Like this:

<form method="post" action="/my-controller/my-action">    @Html.AntiForgeryToken()</form>

Since your controller receiving the post is looking for the anti forgery token, you need to ensure that you add it to your form in the view.

EDIT:

Try building your data in json first:

var formData = $('form[action="/TransportJobAddress/Create"]').serialize();$.extend(formData, {'__RequestVerificationToken': token });//and then in your ajax call:$.ajax({    //...    data:formData    //...});