I am having a curiously weird problem, here is my JS code
function ValidateUser(username) {
var userExists = "somevalue";
$.ajax({
contentType: 'application/json, charset=utf-8',
type: "POST",
url: "/Controller/Validate",
data: JSON.stringify({ username: username }),
cache: false,
dataType: "json",
success: function (response) {
alert(response);
if (response == true) {
userExists = true;
alert("user exists: " + userExists);
} else {
alert("user exists: " + userExists);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('error');
}
});
return userExists;
}
well, the action works fine and validates user correctly, but the function ALWAYS returns “somevalue”…..What gives? My hunch is that it has something to do with a function scope. But how do I resolve this issue.
Because the function you’re calling
$.ajaxfrom returns before the Ajax call completes.The simple answer is to do the work you need to do in the
successfunction, either with an immediate function (as now), or by settingsuccessto an existing function.You could also use jQuery’s
$.whenfunction.