I want to post data to server with ajax call but i am getting an error.
var userdata = {};
userdata["Name"] = "Saran";
var DTO = { 'userdata': userdata };
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/update",
data: JSON.stringify(DTO),
datatype: "json",
success: function (result) {
//do something
alert("SUCCESS = " + result);
console.log(result);
},
error: function (xmlhttprequest, textstatus, errorthrown) {
alert(" conection to the server failed ");
console.log("error: " + errorthrown);
}
});//end of $.ajax()
I have created a function in Default.aspx.cs and tried to access that function with the above call.
[WebMethod]
public static string update(string userdata)
{
return "Posted";
}
Error :
POST http://localhost:33762/Default.aspx/update 401 Unauthorized 52ms
Message "Authentication failed." StackTrace null ExceptionType
"System.InvalidOperationException"
Firstly, you have to set/update to settings.AutoRedirectMode = RedirectMode.Off;
in App_Start/RouteConfig.cs.
Secondly, your ajax payload is not structured properly to make the appropriate call to the update
method. See updates below:
var DTO = { 'userdata': 'Saran' };
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/update",
data: JSON.stringify(DTO),
datatype: "json",
success: function (result) {
//do something
alert("SUCCESS = " + result.d);
console.log(result);
},
error: function (xmlhttprequest, textstatus, errorthrown) {
alert(" conection to the server failed ");
console.log("error: " + errorthrown);
}
});//end of $.ajax()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With