Yii2 and Ajax: the response is not the result of an SQL query

I want to execute an AJAX request using jQuery, but the answer is not the one I want.

Client side:

$.ajax({
    url: "/family?idperson=1234",
    dataType: 'json',
    success: function(res) {
        console.log(JSON.stringify(res, null, 4));
    },
    error: function(err) {                
    }
});

Server side:

public function actionFamily($idperson)
{
    $searchModelFamily = new FamilySearch();
    $dataProvider = $searchModelFamily->searchByIdperson(Yii::$app->request->queryParams, $idperson); // This database query works great.

    Yii::$app->response->format = Response::FORMAT_JSON;
    return $dataProvider;
}

This is the content of the JSON object: It seems that some parts of the SQL query. But I need SQL results.

{
    "query": {
        "sql": null,
        "on": null,
        "joinWith": null,
        "select": null,
        "selectOption": null,
        "distinct": null,
        "from": null,
        "groupBy": null,
        "join": null,
        "having": null,
        "union": null,
        "params": [],
        "where": {
            "idperson": "1234"
        },
        "limit": null,
        "offset": null,
        "orderBy": null,
        "indexBy": null,
        "emulateExecution": false,
        "modelClass": "app\\models\\Family",
        "with": null,
        "asArray": null,
        "multiple": null,
        "primaryModel": null,
        "link": null,
        "via": null,
        "inverseOf": null
    },
    "key": null,
    "db": null,
    "id": null
}
+4
source share
1 answer

It seems that your actionFamily method returns a DataProvider object, not the data you want to receive. If actionFamily is a method in the yii \ rest \ controller, it should work, but I assume that you are using the regular yii \ web \ controller, which will simply return the object as it is.

To get DataProvider data, try changing this ...

return $dataProvider;

in it...

return $dataProvider->getModels();

or change the controller class (if it is a REST function) as described above.

+4
source

Source: https://habr.com/ru/post/1685601/


All Articles