Wurlitzer
Wurlitzer

Reputation: 2919

Wait for function to finish before executing the rest

When the user refreshes the page, defaultView() is called, which loads some UI elements. $.address.change() should execute when defaultView() has finished, but this doesn't happen all the time. $.address.change() cannot be in the success: callback, as it's used by the application to track URL changes.

defaultView();

function defaultView() {
    $('#tout').fadeOut('normal', function() {
        $.ajax({
            url: "functions.php",
            type: "GET",
            data: "defaultview=true",
            async: false,
            success: function (response) {
                $('#tout').html(response).fadeIn('normal');
            }
        });
    });
}

$.address.change(function(hash) {
    hash = hash.value;
    getPage(hash);
});

I'm at a loss as to how to make $.address.change() wait for defaultView() to finish. Any help would be appreciated.

Upvotes: 1

Views: 5728

Answers (3)

Kyle Cureau
Kyle Cureau

Reputation: 19366

I too was told that because of async you can't make javascript "wait" -- but behold an answer :D ...and since you're using jQuery, all the better:

use jQuery's bind and trigger. I posted an answer to a similar problem at How to get a variable returned across multiple functions - Javascript/jQuery

Upvotes: 2

ScottE
ScottE

Reputation: 21630

One option is to hide the $.address (I'm guessing this is a drop-down list) via css, and show it inside the success callback from the ajax method.

Upvotes: 0

Alex Sexton
Alex Sexton

Reputation: 10451

Call it in the success or complete callback. Using delay for timing a callback is unreliable at best. You might even need to put the call to it in the callback to the fadeIn function inside of the success callback.

It doesn't have to be defined inside the success callback, just executed. Both contexts will still be able to use it.

Upvotes: 3

Related Questions