0

I have an ajax call returning html code which is inserted into a container.

Now I need to call a jQuery function to format the gallery, but I can't find a way to ensure that the jQuery function waits for returnedData to be fully loaded/rendered.

As you can see I have tried .ready() but it doesn't work. I have also tried setTimeout, which actually works, but as the returnedData can contain a lot of images, I can't use it as I don't know how long it would take to load all the images.

Any ideas?

$(document).ready(function() {
    $.ajax(url, {type: 'POST', dataType: 'json', data: data, success: success_handler});
});

function success_handler(returnedData) {
    $('.category-images-js').html(returnedData);
    $('.category-images-js').ready(function() {
        // Code to run after all data inside returnedData is fully ready/rendered
    );
}

SOLUTION: This thread: How to know if all elements in a DIV have been fully loaded? worked for me but I had to make a work-around as the code I run, when data inside returnedData is fully ready/rendered, makes the on load trigger 3 times per image.

Pripster
  • 1
  • 1
  • try the **ajaxComplete()** handler. http://api.jquery.com/ajaxcomplete/ – Hamza Abdaoui Jun 22 '17 at 13:35
  • 1
    Possible duplicate of [How to know if all elements in a DIV have been fully loaded?](https://stackoverflow.com/questions/26480844/how-to-know-if-all-elements-in-a-div-have-been-fully-loaded) – Yannici Jun 22 '17 at 13:35
  • _Code to run after all html inside returnedData is fully ready/rendered._ It's unclear what you mean by that. `returnedData` is JSON and has no html inside. – hindmost Jun 22 '17 at 13:40
  • It will help to understand http://api.jquery.com/category/deferred-object/ which ajax uses. – Bindrid Jun 22 '17 at 14:00
  • Personaly I use $.post when doing AJAX calls in jQuery. You might wanna try this `$.post(url, {data: data}, function(response){ $('.category-images-js').html(response); $('.category-images-js').ready(function() { // Code to run after all data inside returnedData is fully ready/rendered ); })` – Bas Pauw Jun 22 '17 at 14:05

1 Answers1

0

I've made my own ajax function so i hope it fits you:

function xhr(u, c) {
    var x = new XMLHttpRequest();
    x.onreadystatechange = function (){
        if (x.readyState == 4 && x.status == 200){
            c(x.responseText)
        }
    };
    x.open("GET", u, true);
    x.send()
}

u = URL

c = Callback function