callback function does not change var when using getJSON function in jQuery
I am trying to change a variable for validation purposes, the changes takes place inside a $.getJSON()
function after the return of certain data.
The problem is after chaining the variable and outside the $.getJSON()
the variable is returned to its original value. Here is the code for that part:
var isValid = true;
// Validate Username
var un = $('#username').val();
if(un.length < 5) {
isValid = false;
$('#ins_username').html('').hide();
$('#msg_username').html('Please fill username, minium 5 Characters').show();
// to append to another msg
} else {
$.getJSO开发者_运维问答N("validateUsername.action", {
'newStudent.users.username': $('#username').val()
},function(json) {
if ( json.jsonData.usernameFound == true ) {
isValid = false;
$('#ins_username').html('').hide();
$('#msg_username').html('Please change username, Username Taken.').show();
alert ("the isValid value inside the getJson() "+isValid);
// the isValid = false here as expected
alert ("JOSN from inside "+json);
} else {
$('#msg_username').html('').hide();
}
});
alert ("the isValid value outside the getJson() "+isValid);
// the isValid = true here, i want the changes to remain
}
I am not sure what have I missed here.
The success
function is a callback, which means it doesn't execute immediately. The alert
at the end is evaluated and executed immediately. When it executes, the callback has not had a chance to update the value of isValid
, so it still shows the original value.
UPDATE: Here's the jQuery documentation on the concept of a callback that should help explain this behavior
精彩评论