L
L
lenkagruzd2018-07-12 18:06:30
Yii
lenkagruzd, 2018-07-12 18:06:30

Yii: Pjax + JQuery.click() + setIntreval. Why is only the last click executed?

Hello.
The view in the foreach loop displays 1 or more PJax.
Inside pjax is a link with a class that is unique to that link.
Sessions are in progress. We are trying to update the time counter.
pjax code:

<?php Pjax::begin([
    'enablePushState' => false,
]); ?>
<?php 
         $old_date = new DateTime($order['creation_time']);
         $old_date->add(new DateInterval('P0Y0M0DT0H30M0S'));
         $now_date = new DateTime($actualtime);
         $interval = $old_date->diff($now_date, false);
         echo "<a href='/cart/gettime?id={$order['game_id']}' class='gettime'>".$interval->format("%I : %S")."</a>";
?>
<?php Pjax::end(); ?>

Gettime controller code:
public function actionGettime() {

    $id = Yii::$app->request->get('id');
    if(!empty($id)) {
      $session = Yii::$app->session;
      $session->open();
      $order = $session['cart'][$id];
      $actualtime = Yii::$app->formatter->asDate('now', 'php:Y-m-d H:i:s');
      
      return $this->renderAjax('gettime', compact('order', 'actualtime'));
    } else {
      return '0';
    }
  }

The view( gettime ) returned by the controller matches the code in Pjax.
Script code:
$(document).ready(function() {
       setInterval(function(){ 
             $('.gettime').each(function() {
                    $(this).click();
             });
        }, 1000);
    });

What do we end up with:
  • Everything works successfully if we have only one iteration in the foreach loop.
  • If there is more than one iteration, then Pjax updates only the last iteration.

Perhaps there are more elegant solutions, but there is a desire to understand why this particular design does not allow updating.
If you replace JQuery.click() with, for example,
var g = $(this).attr('id');
console.log(g);

, then we get the result we need for each element.
The interval increased, the delay for click () was set. All the same. In which direction to dig?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question