tags:

views:

39

answers:

1

Hello. I'm having issues with some jQuery code I have.

Using $.each I am looping through a few values and calling some php code. After this $.each loop is finished, I would like to load a div with certain content. I have tried loading the div after the $.each statement, but the load statement is still executed first, displaying the wrong value. When I put this load inside the $.each it works, although it loads after each iteration instead of at the end. Any ideas?

Here is the relevant part my code:

$.each(steps, function(n,step){
            $.post("utility.php", {
                utility: "getStepValue",
                step: step
            },
            function(data) {
                // offset clock
                var step_value = data;
                $.post("utility.php", {
                    utility: "offsetClock",
                    step_value: step_value
                },
                function(data){
                    // when load statement inserted here, it works fine
                });
            });
        }
    });

    // this statement finishes before the $.each, showing the wrong value
    $("#clock").load("utility.php", {
        utility: "displayClock"
    });
+1  A: 

Get the number of steps. Then, do the $("#clock").load("utility.php" ... inside the second callback in the loop only if the current index is the same as the number of steps - 1. Something like this:

var count = steps.length;
$.each(steps, function(n,step){
            $.post("utility.php", {
                utility: "getStepValue",
                step: step
            },
            function(data) {
                // offset clock
                var step_value = data;
                $.post("utility.php", {
                    utility: "offsetClock",
                    step_value: step_value
                },
                function(data){
                  if(n == count - 1){
                    $("#clock").load("utility.php", {
                      utility: "displayClock"
                    });
                  }
                });
            });
        }
    });
Seb
Doh! That makes sense, thanks. Although I still wonder why these functions are not performed in linear order?
Domenic
They are processed in order, the problem is the requests you're doing are asynchronous, which means they are started and, when all the data comes back, the callback function is called. In the meantime, the rest of the code is executed.
Seb
That's to avoid locking the whole JS engine, so the user gets a more smooth UI experience :)
Seb
Ah yes, the A in AJAX, thanks again!
Domenic