Rui Silva
Rui Silva

Reputation: 3

Jquery compare the height of to divs

I want compare the height of to div and append side add while the side div get the same size off the other div, but my code get a infinity loop.

//the i var its just for testing with a non infinity loop
var i = 0;
while($('#lista-body').height() > $('#ads-side').height() && i < 10){
    $.post("getADSSide.php" , { cliente: '<?=$clienteCrypt?>' }, function(data){            
        if (data != '' || data != undefined || data != null){
            setTimeout(function(){ $('#ads-side').append(data);}, 1000);
        }
    });
    i++;
}

Upvotes: 0

Views: 45

Answers (1)

Ajax runs after the loop completes.

Synchronous execution means that the client waits for the method to complete execution and return its results before executing the next JavaScript statement or evaluating the next term of an expression.

Asynchronous execution means that immediately after the client calls the method, it continues to execute the next JavaScript statement or to evaluate the next term of an expression whether or not the asynchronous method completes and returns results.

From the Progress Data Objects Guide and Reference

Ajax ($.post, or more specifically, the callback function) is an asynchronous action. You are essentially attempting to use synchronous code to wait on an asynchronous action, which will never work (or if it does, it will do so very badly). Especially as your synchronous code continues to execute further asynchronous Ajax instructions.

If you want to fill the div until its height is sufficient, calculate the height inside the callback, and if there is not enough content, re-execute the Ajax call:

function fillAds() {
    $.post("getADSSide.php" , { cliente: '<?=$clienteCrypt?>' }, function(data){            
        if (data != '' || data != undefined || data != null){
            setTimeout(function(){
                $('#ads-side').append(data);
                if($('#lista-body').height() > $('#ads-side').height()) {
                    fillAds();
                }
            }, 1000);
        }
    });
}

With another fillAds(); call somewhere external to this code.

Notice also, that by making this simple change, in the event that the asynchronous action fails (e.g. data is undefined, empty, null, or the method fails to execute entirely) we don't attempt to make further Ajax calls. Huzzah! Free error handling!

Upvotes: 1

Related Questions