Why can't I get the calculated height of the content inserted in response to a jQuery AJAX request?

I am sure that this has been discussed repeatedly, but I'm at a standstill. I use jQuery to call an AJAX ASP.NET web service that returns some HTML. This part is working fine.

I want to do some calculations at the height of the returned HTML, but when the call is made for the first time, I get a height of 0. I know that my calculations only happen until the AJAX call is completed, because on the second attempt it works. If I clear the cache, it returns 0 again.

I need to fire an event after rendering html. I have tried both global and local events such as ajaxComplete.

$.ajax({
    type: "POST",
    url: "Webservices/Service.asmx/HelloWorld",
    data: "{}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
        $("#OverlayContent").html(msg.d);
    }
    complete: function(msg) {
        alert($("#OverlayContent").height());
    } 
});

I appreciate any help.

+3
3

, , html DOM. setTimeout . :

$.ajax({
    type: "POST",
    url: "Webservices/Service.asmx/HelloWorld",
    data: "{}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
        $("#OverlayContent").html(msg.d);
        setTimeout(function(){ getHeight();},100);
    }
});

function getHeight(){
    // If our height is 0, set a new timeout and we'll check again
    if($("#OverlayContent").height() === 0){
        setTimeout(function(){ getHeight() }, 100);
    }
    else{
        alert("The height is: " + $("#OverlayContent").height());
    }
}

html DOM .

+7

, , , , AJAX , . 200 OK.

, , jQuery queue() :

success: function(msg) {
        $("#OverlayContent").html(msg.d).queue(function(){
            alert($("#OverlayContent").height());
            $(this).dequeue();
        })
    }

dequeue() .

.

+2

I can’t fully understand your question, but you can try to set the update code in a timeout that starts immediately after the event is completed ...

//..your other code here

complete:function(m) {
    setTimeout(function() {
        alert($("#OverlayContent").height());
    },1);
}

//...the rest of your code
+1
source

Source: https://habr.com/ru/post/1710029/


All Articles