Yii: Render Partial and Return to AJAX in JSON format

Whatever Kitchen picture Whatever Kitchen · Jul 26, 2012 · Viewed 12k times · Source

As per subject above, I have some confusion on the return of the data. So, when I try to return the render partial view data from my controller to AJAX the code will be as follows.

JQuery AJAX:

$.ajax({
         url: "<?php echo $this->createUrl('ajaxrequest');?>",
         type: "POST",
         data: {affordableCarPrice: ccarprice},                        
         success: function(data){
            console.log(data);
         }
});

Yii Controller

public function actionAjaxrequest(){               

        $carListingView[] = $this->renderPartial("_budgetNewCarsListing", array('newCarListing' => $newCarListing), true);
        $carListingView[] = $this->renderPartial("_budgetUsedCarsListing", array('usedCarListing' => $usedCarListing), true);

        var_dump($carListingView);
}

The codes inside the controller, I had minimize it and when I log the return data, it gives me the correct one. But, when I use json_encode the array in the controller, and I go back see the return data, it gives me the wrong one.

Despite I set dataType: 'json' and contentType: "application/json; charset=utf-8", in the JQuery ajax. Or header('Content-type: application/json'); in the controller. It still returns the wrong data.

Need help on this very badly, as I couldn't resolve this problem for like almost 2 days. :(

Answer

ernie picture ernie · Jul 26, 2012

To return the data to the JS:

public function actionAjaxrequest(){               
    $carListingView[] = $this->renderPartial("_budgetNewCarsListing", array('newCarListing' => $newCarListing), true);
    $carListingView[] = $this->renderPartial("_budgetUsedCarsListing", array('usedCarListing' => $usedCarListing), true);

    echo CJSON::encode($carListingView);
}

Two important things. The first is is the third argument to renderPartial(). As the doc states:

whether the rendering result should be returned instead of being displayed to end users

This means instead of echo'ing out the rendered view, it'll be returned as a string.

The second is the CJSON::encode(), which takes the variable and converts it to a JSON representation, which javascript will be able to handle. CJSON::encode()'s advantages are that it doesn't require any particular version of PHP (json_encode requires PHP 5.2 or newer), and that it can handle Active Records.