I have a function that forces a user to log in if they click submit and it finds they aren’t logged in:
$('#buildFormQueue').submit(function(){
return $.dialogs.forceLogin();
});
I need forceLogin() to return true if the user login has succeeded.. the problem, however, is that the login form is loaded by ajax and the forceLogin() function is finished executing before the user even sees the login dialog.
forceLogin : function(){
if(!$.loggedIn){
$.ajax('/index.php?act=loginDialog', {success:function(data){
$("#dialog-message").html(data)
.attr('title', 'Please Log In')
.dialog({
modal: true,
buttons: {
'Cancel': function(){
$(this).dialog('close');
},
'Log In': function(){
$this = $(this);
$.post('/index.php?act=loginDialog&mode=post', {
'username' : $("#dialog-message :input[name='username']").val(),
'password' : $("#dialog-message :input[name='password']").val()
}, function(data){
if(data == "true"){
$this.dialog('close');
$.loggedIn = true;
}else{
$this.find('div').slideDown('slow');
}
});
},
},
width: 400,
position: ['center', 50],
});
$('#dialog-message :input').keypress(function (e) {
if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
$('.ui-dialog-buttonset :last').click();
return false;
} else {
return true;
}
});
}});
return false;
}else{
return true;
}
},
Is there any way of forceLogin() to return from within the 'Log In': function()?
There is not a way to do this because the
forceLoginfunction will complete synchronously while the ajax request will complete asynchronously.The standard way of working around this though is to have
forceLoginreturn nothing and instead take in a callback function to which the result of the login will later be passed. For exampleThe calling code then just needs to move it’s handling logic into a lambda.
Old Way:
New Way: