1

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);
Eli
  • 14,779
  • 5
  • 59
  • 77
skolind
  • 1,724
  • 6
  • 28
  • 51

3 Answers3

6

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()

Draculater
  • 2,280
  • 1
  • 24
  • 29
  • 2
    @Kolind Without the `var`, `$this` is declared as a global rather than a local variable. http://stackoverflow.com/q/1470488/ – Jonathan Lonowski Aug 23 '12 at 18:41
  • @JonathanLonowski Awesome. Thanks a lot for this :) Amazing that 'var' can turn the whole function to work. I love programming :) – skolind Aug 23 '12 at 18:43
  • 2
    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()`. – Draculater Aug 23 '12 at 18:46
2

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

Hope this will help you.

Community
  • 1
  • 1
Kundan Singh Chouhan
  • 13,952
  • 4
  • 27
  • 32
-1

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.

user1330271
  • 2,601
  • 3
  • 20
  • 26