skolind
skolind

Reputation: 1754

jQuery - setInterval with $.each

I am about to rip my hair of the head. I'm trying to interact with my PHP function, which is measuring some times: timeSince() a post is posted.

I do NOT need a plugin for doing this in jQuery, thanks :o)

But I wan't to run the $.get() on all .post-box-time div's so therefore I am using $.each. But it's only updating the last element, but giving me the result for the other divs to. -> It's like it's not doing the $.each()..

Here is my code:

setInterval(function() {
        $('.post-box-time').each(function() {
            var time = $(this).attr('data-time');
            $this = $(this);

            $.get("sys/calls.handler.php", { do: 'timeSince', data: time },
                function(data){
                    $this.html(data);
                });
        }); // each function
    }, 1000);

Upvotes: 1

Views: 852

Answers (3)

Draculater
Draculater

Reputation: 2278

Well you should throw a var before declaring $this.

You were declaring it as a global variable as opposed to declaring it inside the scope (which is what var does) of each function being run by each().So when your response callback was actually being fired off, your loop had already completed and set global variable $this (or window.$this) to the value of the last .post-box-time it found while looping via each()

Upvotes: 6

user1330271
user1330271

Reputation: 2691

I think this within the each function is a reference to the raw DOM element. The .each gives indexes starting from 0, so you should do $('.post-box-time:eq(' + i + ')') instead.

Upvotes: -1

Kundan Singh Chouhan
Kundan Singh Chouhan

Reputation: 14282

Use async option. This Thread is related with your question.

Hope this will help you.

Upvotes: 2

Related Questions