O
O
Oleg2018-12-19 10:58:24
JavaScript
Oleg, 2018-12-19 10:58:24

Yii2 + jquery: Why does getJSON redirect to request page after receiving?

Good afternoon!
I can’t overcome the problem :( There is a task: to poll the server through a js timer and, depending on the data received, manipulate the elements on the page.

The js file connected via assets has the following code:

var timerId = setTimeout(function tick() {
        var url =  location.protocol + "//" + location.host+"/waiter/locations/statuses?restaurant_id="+$(".ServiceLocations").attr('data-restaurant-id');
        $.getJSON(url, function(data) {
            // мой код обработки полученных данных            
        });
        timerId = setTimeout(tick, 1000);
    }, 1000);

This code requests the data that the statuses action of the locations controller of the waiter module returns:
...
public function actionStatuses()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $data = ['id'=>2,'text'=>'zzz']; // примерный массив данных
        return $data;
    }
...

As a result, as soon as $.getJSON is called, the page reloads to the url and I see just an array of data. Why am I being redirected to the request page?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
Oleg, 2018-12-19
@volego

Thank you all, the problem was solved by moving the update function from the included JS file to the view:

$url = Url::to(['locations/statuses', 'restaurant_id' => $restaurant->id]);
    $script = <<< JS
        var timerId = setTimeout(function tick() {
        $.getJSON('$url', function(data) {
            data.forEach(function(item){
                //обработка массива полученных данных
            });
        });
        timerId = setTimeout(tick, 1000);
    }, 1000);
JS;
    $this->registerJs($script, yii\web\View::POS_READY);

N
nvdfxx, 2018-12-19
@nvdfxx

return false at the end of the timer

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question