The required anti-forgery form field "__RequestVerificationToken" is not present - ajax

There really is a lot of info about this problem in internet, but nothing is helped me.
That is my client code:
var token = $('form[action="/Storage/AddReceipt"] input[name="__RequestVerificationToken"]').val();
var addAntiForgeryToken = function(data) {
data.__RequestVerificationToken = token;
return data;
};
var success = function (result) {
alert(result.success);
};
$.ajax({
url: '#Url.Action("AddReceipt", "Storage")',
type: 'POST',
contentType: 'application/json',
data: addAntiForgeryToken({ Number: 1, BatchDate: '24/03/2015' }),
success: success,
error: function (xhr, textStatus, errorThrown) {
alert(errorThrown);
}
});
and controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddReceipt(...) {...}
and server response to my requerst -
The required anti-forgery form field
"__RequestVerificationToken" is not present.
but correct token is sending:
return JSON.stringify(data);
and
$.ajax({
...
data: $('form[action="/Storage/AddReceipt"]').serialize(),
...
}
doesnt help too.

You missed to add the __RequestVerificationToken to the request headers. Add it as follows.
$.ajax({
url: '#Url.Action("AddReceipt", "Storage")',
type: 'POST',
contentType: 'application/json',
headers:{__RequestVerificationToken : token},
data: JSON.stringify(addAntiForgeryToken({ Number: 1, BatchDate: '24/03/2015' })),
success: success,
error: function (xhr, textStatus, errorThrown) {
alert(errorThrown);
}
});
We must add the anti forgery token to the request header.

Related

how to send ajax POST request

I am using this method to send post request but it gives me error 500 internal error for jquery.1.11.1.min.js.
$(document).ready(function () {
$.ajax({
type: "POST",
url: '#Url.Action("cashondelivery", "Home")',
data: "",
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function (result) {
alert(result);
},
error: function (data) {
alert(data);
}
});
});
//this is action method in controller
[HttpPost]
public ActionResult cashondelivery(productinfoModel mmodel)
{
return View();
}
try to call the url in DHC(chrome plugin),the response status code 500 means server internal error, it's the server-webapp developer's mistake. not your mistake.

Ajax fetching data.But also showing error with datatype Json.But working with datatype html

I am trying to fetch the data from php file by passing dynamic query string on ajax URL section.But while I changing datatype html to json. It is popping up error
jQuery(".nks_cc_trigger_element").click(function(){
var str = jQuery(this).attr("data-product_id");
jQuery.ajax({
url: "/ajax_product.php?q="+parseInt(str),
type: 'POST',
dataType: 'json',
success: function(result){
jQuery("#nks-content-1 > div").html(result);
console.log(result);
},
error: function(jqXHR,error, errorThrown) {
if(jqXHR.status&&jqXHR.status==400){
alert(jqXHR.responseText);
}else{
alert("Something went wrong");
alert(jqXHR.responseText);
}
}
}).done(function() {
});
>>PHP CODE
echo json_encode($data) ;
Use the data key/attribute and use the POST method, but don't pass the queries through the URL.
$(".nks_cc_trigger_element").click(function(){
var str = $(this).attr("data-product_id");
$.ajax({
url: "ajax_product.php",
type: 'POST',
dataType: 'json',
data: //json data,
success: function(result){
//success code
},
error: function(jqXHR, error, errorThrown) {
//error code
}
});
});

Ajax POST request to ODATA service throws Invalid HTTP status code 501

I have the following code which I wish to use for inserting a record into an entity of an ODATA service.
The post request throws a XMLHttpRequest cannot load Invalid HTTP status code 501.
Apparently GET request works fine. Can anyone suggest a way to find out the problem ? Does my WCF Service has a problem ?
var data = { application_id: 777 , user_id: 'test' };
var data = JSON.stringify(data);
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
datatype: 'json',
url: oDataURL + 'application_admins',
data: data,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest) {
account = data.d;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
}
});

How can I get response header using AJAX

I'm trying to get response header using AJAX, but it doesn't work. Apparently I did't do it right:
$.ajax({
type: 'GET',
url:'http://www.somesite.com/',
data: formData,
success: function(data, textStatus, XMLHttpRequest){
alert(XMLHttpRequest.getResponseHeader('some_header'));
}
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.getResponseHeader('some_header'));
}
});
I also try this one:
$.ajax({
type: "GET",
url: 'http://www.somesite.com/',
complete: function(xhr) {
alert(xhr.getAllResponseHeaders());
}
});
Any help?
You are missing a comma.
success: function(data, textStatus, XMLHttpRequest){
alert(XMLHttpRequest.getResponseHeader('some_header'));
}, // <-------------

jQuery ajax POST request with application/json

I want to make a POST request to the remote server from jQuery. When I write code like this
$.ajax({
type: 'POST',
url: 'http://mysite:8080/orderService/order/send',
crossDomain: true,
data: JSON.stringify(orderSendRequest),
dataType: 'json',
success: function(responseData, textStatus, jqXHR) {
var value = responseData.someKey;
},
error: function (responseData, textStatus, errorThrown) {
alert('POST failed.');
}
});
Everything is ok, but I want ContextType to be application/json, and when I add this line to the code the request doesn't work and I have the following error:
XMLHttpRequest cannot load http://mysite:8080/orderService/order/send. Origin null is not allowed by Access-Control-Allow-Origin.
$.ajax({
type: 'POST',
url: 'http://mysite:8080/orderService/order/send',
crossDomain: true,
data: JSON.stringify(orderSendRequest),
dataType: 'json',
contentType : 'application/json; charset=utf-8',
success: function(responseData, textStatus, jqXHR) {
var value = responseData.someKey;
},
error: function (responseData, textStatus, errorThrown) {
alert('POST failed.');
}
});
I don't believe json supports crossDomain. Research using jsonp datatype instead.

Resources