V
V
Vladislav Bushuev2015-06-28 18:01:21
JavaScript
Vladislav Bushuev, 2015-06-28 18:01:21

What am I doing wrong with the $.post request?

Hello!
I am not strong in JS, but I need to do ajax loading through the $.post function.
js code:

$.post(
            "<?= Url::toRoute(['/user/default/get', 'id' => 1]); ?>", {
                _csrf: "<?= Yii::$app->request->getCsrfToken() ?>",
            },
            function(data){
                var info = $.parseJSON(data);
                if(info.status == 'off') {
                    alert('off')
                } else {
                    alert('on');
                }
            }
        );

Action where the request goes:
public function actionGet($id)
    {
        Yii::$app->response->format = Response::FORMAT_JSON;

        $online = true;
        if($online) {
            $data['status'] = 'on';
            return $data;
        } else {
            $data['status'] = 'off';
            return $data;
        }
    }

And in general, nothing happens, except for the error in the console "Uncaught SyntaxError: Unexpected token o".
What am I doing wrong?
Where is the mistake?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladislav Bushuev, 2015-06-28
@redstar

If you do it like this:

$online = true;
        if($online) {
            $data['status'] = 'on';
            return json_encode($data);
        } else {
            $data['status'] = 'off';
            return $data;
        }

So it's not about JS, but about Yii.
Why does not it work
Yii::$app->response->format = Response::FORMAT_JSON;
?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question