0

I have some links on webpage that redirect a user to pages where being logged in is required. So if a user is not logged in, I want to show him a modal window with a message to 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 you can see there are two asynchronous calls in the function, so I need somehow make tag to wait for the function to fully execute.

And some tag

<a href="only_for_logged_in.ph" onclick="return isLoggedIn();">Click</a>

PS. The pages that tags are linking to are protected against access of users that are not logged in, so you don't need to worry about security, I just need to show to modal window without redirecting a user, but I also want to keep the url in href="", so when a logged in user clicks on it, it will redirect him to the page.

Stevik
  • 1,092
  • 2
  • 16
  • 37
  • I think you are wanting to pass a callback to this function which will be called once the second ajax is successful. – KJ Price Apr 14 '15 at 20:38

1 Answers1

0

Given that the $.get() method is asynchronous, you cannot return a value right after it, because it hasn't already finished executing, so what you need is to pass your isLoggedIn() function a callback, and call it when the $.get() method calls the callback provided to .done.

Here's an 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 your callback when .get finishes working
                callback(false);
            });
        // I'm assuming that if data is not 2, the user is logged in
        } else  callback(true);
    });
}

isLoggedIn(function(result) {
    if (result) {
        // The user is logged in, do something
    } else {
        // The user is not logged in, do something else
    }
});
Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128