javascript - onClick wait for returned value -


this question has answer here:

i have links on webpage redirect user pages being logged in required. if user not logged in, want show him modal window message log in.

function isloggedin(){         var requirelogincheckstatusurl="require_login.php?check_login=1";         $.get(requirelogincheckstatusurl).done(function(data) {             if(data == 2){                 var requireloginmodalurl = "require_login.php?ajax=1";                 $.get(requireloginmodalurl).done(function(data) {                      $('body').prepend(data);                     $('body').addclass('stop-scrolling');                     return false;                 });                 }              });       return true; } 

as can see there 2 asynchronous calls in function, need somehow make tag wait function execute.

and tag

<a href="only_for_logged_in.ph" onclick="return isloggedin();">click</a> 

ps. pages tags linking protected against access of users not logged in, don't need worry security, need show modal window without redirecting user, want keep url in href="", when logged in user clicks on it, redirect him page.

given $.get() method asynchronous, cannot return value right after it, because hasn't finished executing, need pass isloggedin() function callback, , call when $.get() method calls callback provided .done.

here's example:

function isloggedin(callback) {     var requirelogincheckstatusurl="require_login.php?check_login=1";     $.get(requirelogincheckstatusurl).done(function(data) {         if(data == 2){             var requireloginmodalurl = "require_login.php?ajax=1";             $.get(requireloginmodalurl).done(function(data) {                 $('body').prepend(data);                 $('body').addclass('stop-scrolling');                  // call callback when .get finishes working                 callback(false);             });         // i'm assuming if data not 2, user logged in         } else  callback(true);     }); }  isloggedin(function(result) {     if (result) {         // user logged in,     } else {         // user not logged in, else     } }); 

Comments

Popular posts from this blog

css - SVG using textPath a symbol not rendering in Firefox -

Java 8 + Maven Javadoc plugin: Error fetching URL -

order - Notification for user in user account opencart -