I have a .net project in the framework 4.5.1
When I use ajax
like below, it works and the debugger hits the page_load
event:
$.ajax({
"async": true,
"crossDomain": true,
type: "POST",
url: "Advanced.aspx",
contentType: "application/json; charset=utf-8",
success: function (ms) {
alert('success');
}
})
In my advanced.aspx.cs, I have the method below:
[System.Web.Services.WebMethod, ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = false)]
public static string SaveChange(string myval)
{
//dummy code for test purposes.
string u = myval + "X";
return u;
}
I want to hit this method via ajax
. To do this, I am updating my ajax
call like below:
$.ajax({
"async": true,
"crossDomain": true,
type: "POST",
url: "Advanced.aspx/SaveChange",
data: {username:"test"},
contentType: "application/json; charset=utf-8",
success: function (ms) {
alert('success');
}
})
However, it gives me 401:unauthorized error
when i do it in that way, shown below:
How can I fix this? Tried lots of things for the last few hours, no luck.. Any help would be appreciated.
EDIT: I’ve used async
and crossDomain
hoping to fix this issue, didn’t help. Normally they don’t exist in my ajax call, nothing changes.
2
Answers
Found the answer here: ASP.NET Calling WebMethod with jQuery AJAX "401 (Unauthorized)"
I have used
settings.AutoRedirectMode = RedirectMode.Off;
instead ofRedirectMode.Permanent
in~/App_Start/RouteConfig.cs
, which fixed the issue.Try updating your AJAX JS to: