I'm building an AspNet Core Razor Pages Web site and I'm unable to execute a JQuery AJAX POST call to the server. Here the server side code:
public async Task<JsonResult> OnPostUpdateQRCodeAsync(int id, string name, string description)
{
...
}
And here my ajax client side code:
function UpdateQRCodeData(id, name, description) {
var url = "?handler=UpdateQRCode";
var token = getToken();
debugger
return $.ajax({
type: "POST",
url: baseUrl + url,
headers: { "RequestVerificationToken": token },
data: {
id: id,
name: name,
description: description
},
contentType: "application/json;",
dataType: "json",
success: function (response) {
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
The getToken() function gets Antiforgery token from page.
The error I receive is the following:
SyntaxError: Unexpected token < in JSON at position 0
What am I doing wrong? Can anyone help me?
Thanks
Here is a working demo:
cshtml(When use @Html.AntiForgeryToken()
,html will have a hidden input __RequestVerificationToken
):
@Html.AntiForgeryToken()
<button onclick="UpdateQRCodeData(1,'name','description')">Ajax</button>
js(Parameters of handler OnPostUpdateQRCodeAsync is not get from body,so I remove contentType: "application/json;",
):
<script>
function UpdateQRCodeData(id, name, description) {
var url = "?handler=UpdateQRCode";
return $.ajax({
type: "POST",
url: url,
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
data: {
id: id,
name: name,
description: description
},
//contentType: "application/json;",
dataType: "json",
success: function (response) {
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
</script>
cshtml.cs:
public async Task<JsonResult> OnPostUpdateQRCodeAsync(int id, string name, string description)
{
return new JsonResult(new object { });
}