I have the following jQuery code:
var isUsernameAvailable = false;
function CheckUsername(uname) {
$.ajax({
method: "POST",
url: "IsUsernameAvailable.asmx/IsAvailable",
data: { username: uname },
dataType: "text",
success: OnSuccess,
error: OnError
}); // end ajax
} // end CheckUsername
function OnSuccess(data) {
if (data == true) { // WHY CAN'T I TEST THE VALUE
isUsernameAvailable = true;
} else {
isUsernameAvailable = false;
$('#error').append('Username not available');
}
}
function OnError(data) {
$('#error').text(data.status + " -- " + data.statusText);
}
And a simple Web Service:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class IsUsernameAvailable : System.Web.Services.WebService {
public IsUsernameAvailable () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public bool IsAvailable(string username) {
return (username == "xxx");
}
}
I just can’t read the return value from my web service. When I print out the value in the callback function (data parameter) I get true or false (note the preceding whitespace).
When I print out data.d, it says undefined. FYI, the web service method gets hit each time.
You have the
dataTypespecified astext. This would lead me to believe that the response you’re getting is actually a string and not a boolean value. Switching the dataType tojsonwould give you a Javascript object.Edit: The reason for the parsererror is because the boolean that you are returning is actually a .NET boolean converted to a string. When
.ToString()ends up being called for the actual HTTP response, it ends up beingTrueorFalse. In JSON, boolean values aretrueorfalse(notice the casing). When jQuery is trying to parse the response, it doesn’t think it’s a correct boolean and throws the error.Depending on what ASP.NET flavor you are using, you have a few options. If you’re using MVC or the Web API, just return like this:
If you aren’t using either of those technologies, then it might be best to change your return type to a string and then call:
You will need to import the
System.Web.Script.Serializationnamespace for the previous code snippet to work.