I'm with troubles to connect javascript with asp.net webforms method via ajax and json.
I have the javascript in one folder and page.aspx in the other for example: - Account/createUser.aspx - Script/actions/createuser.js
I already tried many things, for example, use before the method [Webmethod], in the ajax action change many things, but nothing works. In mostly of tentatives the google chrome give the error:
POST .../Account/createUser.aspx/CheckUserName 401 (Unauthorized)
If I remove in javascript lines like: "dataType: json" and "contentType: application/json; charset=utf-8" the error disappears and enter on "complete" line...
I need instructions to resolve this problem... I search a lot of posts, follow many tutorials and nothing means work. For example: change my webconfig to accept any users, my routeconfig.cs...
Is something faling? What? Do I need to declare something to use json?
Javascript:
$("#USUserName").change(function () {
alert($("#USUserName").val());
$.ajax({
type: "POST",
url: "createUser.aspx/CheckUserName",
data: '{username: "' + $("#USUserName").val() + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
complete: function (jsondata, stat) {
if (stat == "success") {
var response = JSON.parse(jsondata.responseText).d;
alert((response));
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert();
}
});
aspx.cs code:
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string CheckUserName(string username)
{
var existUser = context.user.Where(us => ((us.username).Equals(username))).Count();
string returnValue = string.Empty;
if (existUser.Equals(0))
{
returnValue = "test- yes!";
}
else
returnValue = "test- no!";
return returnValue;
}