Saad Mahmood
Saad Mahmood

Reputation: 185

Getting extra data in ajax in Yii2

i am getting data from the ajax call but also getting unnecessary data like all the data from my php files as you can see in the image below. How can I solve this issue? image showing json data but with unnecessary data

controller file

    public function actionAllDrivers()
    {
    $query = new Query;

    $query  ->select(['*']) 

            ->from('driver')

            ->join(  'INNER JOIN',

                    'car',

                    'car.reg_no = driver.reg_no'

                );

    $car2 = $query->all();
    echo json_encode($car2);
    return $this->render('AllDrivers', ['car2'=>$car2,
    ]);

PHP file

    <?php
    $script = <<< JS
        $.get('index.php?r=car/all-drivers',function(data)
        {
           //dataJson = $.parseJSON(data);
           alert(data);
        });
    JS;
    $this->registerJs($script);
    ?>

Upvotes: 1

Views: 143

Answers (1)

Agam Banga
Agam Banga

Reputation: 2693

You are rendering the view after echoing the json. Simple exit will suffice, Check the answer

 if(Yii::$app->request->isAjax)
 {
     echo json_encode($car2);
     exit;
 }

Upvotes: 1

Related Questions