I'm trying to pass the anti-forgery token inside each ajax call for CSRF protection. the problem is I have two POST ajax methods in one view and one of them passes and the other pops an error The required anti-forgery form field "__RequestVerificationToken" is not present. although I'm passing it. What to do so I can be able to pass token to each ajax? Is there a better approach?
$(document).ready(function () {
//toastr.success('Success messages');
var token = $("[name='__RequestVerificationToken']").val();
function RecSLAData() {
SLAData();
var account = $('#Account_ID').val();
//***Empty LOB for another selection***//
$('#Duration').children().remove();
$.ajax({
type: 'POST',
url: '/Add_Request/GetRecSLA/',
data: {
__RequestVerificationToken: token,
acc: account,
},
success: function (result) {
//***loop on results and add to LOB***//
$.each(result, function (k, SubAccounts) {
$("#Duration").append('<option value="' + SubAccounts.Value + '">' + SubAccounts.Text + '</option>');
//$('<option>').val(v.Sub_Account_ID).text(v.Sub_Account_Name).appendTo('#LOB');
});
}
});
};
$('#Account_ID').on('change', function () {
var account = $('#Account_ID').val();
var Emp = $('#Employee_no').val();
var Operation_Date = $('#Operation_Date').val();
// $('#LOB').children('option:not(:first)').remove();
$('#LOB').children().remove();
$.ajax({
type: 'POST',
url: '/Add_Request/GetData/',
data: {
__RequestVerificationToken: token,
acc: account,
},
success: function (result) {
$.each(result, function (k, SubAccounts) {
$("#LOB").append('<option value="' + SubAccounts.Value + '">' + SubAccounts.Text + '</option>');
});
}
});
I added @html.anitforgerytoken() at the form i'm sending . Also added [ValidateAntiForgery] above each post method i'm sending data to in the controller. the solutions i tried : antiforgery for ajax
I'm stuck here. I really appreciate your help.