how to populate gridview from ajax call using Yii2

2019-07-14 14:02发布

In my project, I have created a search box. when I type something and click the button "get info" I get all information in console window using ajax call. now I want to populate this data in yii2 gridview. data will different at every runtime. I want to give this data to $dataprovider of gridview is it possible??

here is code- CompaniesController.php

public function actionCompanyinfo(){     

    $text_in_search = $_GET['text_in_search'];
    $left_items_cat = ltrim($_GET['left_items_cat']);

    if($left_items_cat == "Companies"){

         $query = (new \yii\db\Query())
                ->select(['c.name', 'c.id'])
                ->from(['companies as c'])
                ->where('c.name LIKE :query') 
                ->addParams([':query'=>'%'.$text_in_search.'%'])
                ->all(); 

        $response['comapnies_matching'] = $query;
            return \yii\helpers\Json::encode([
        $response
    ]);  

    }
}

companies/index.php

$form = ActiveForm::begin();
 $typeahead = $form->field($model, 'name')->textInput(['maxlength' => true]);

$getinfobtn = Html::SubmitButton( 'Get info', [ 'class' => 'btn btn-success' , 'id' =>'getinfo']) ;
   ActiveForm::end();  

myjsfile.js

$("#getinfo").click(function(){
        var text_in_search = $("#companies-name").val();
        var left_items_cat = $('#left-items li.active').text();
        var url = "index.php?r=companies/companyinfo";

        $.ajax({
        url: url,
        dataType: 'json',
        method: 'GET',
        data: {text_in_search,left_items_cat},
        success: function (data, textStatus, jqXHR) {           
             // $( "#country"+id ).html(data[0].countries);
             console.log(data[0]);
           // **want to show this data in yii2 grid view**
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log('An error occured!');
            alert('Error in ajax request');
        }
    });

console window

comapnies_matching
:
Array(3)
0
:
{name: "ADC Therapeutics Sarl", id: "402"}
1
:
{name: "ADC Therapeutics Sarl", id: "407"}
2
:
{name: "ADC Therapeutics Sarl", id: "412"}

how to show/ populate this data in gridview??

标签: json yii2
2条回答
唯我独甜
2楼-- · 2019-07-14 14:33

CompaniesController.php

public function actionCompanyinfo(){     

$text_in_search = $_GET['text_in_search'];
$left_items_cat = ltrim($_GET['left_items_cat']);

if($left_items_cat == "Companies"){

     $dataProvider= (new \yii\db\Query())
            ->select(['c.name', 'c.id'])
            ->from(['companies as c'])
            ->where('c.name LIKE :query') 
            ->addParams([':query'=>'%'.$text_in_search.'%'])
            ->all(); 

    return $this->renderPartial('gridview', [
        'dataProvider' => $dataProvider,
    ]); 

}}

You need to render the gridview in gridview.php view file

myjsfile.js

$("#getinfo").click(function(){
    var text_in_search = $("#companies-name").val();
    var left_items_cat = $('#left-items li.active').text();
    var url = "index.php?r=companies/companyinfo";

    $.ajax({
    url: url,
    method: 'GET',
    data: {text_in_search,left_items_cat},
    success: function (data, textStatus, jqXHR) {           
         //set the ajax response as your html content 
         $('#myDiv').html(data);
    },
    error: function (jqXHR, textStatus, errorThrown) {
        console.log('An error occured!');
        alert('Error in ajax request');
    }
});
查看更多
甜甜的少女心
3楼-- · 2019-07-14 14:52

You could render and return HTML of the Gridview from your controller, and then when you get the response. put the HTML code where you want to display it, probably where the current Gridview is contained.

Edit, added code example:

public function actionCompanyinfo(){
    $requestData = \Yii::$app->request->get();
    $text_in_search = isset($requestData['text_in_search']) ? $requestData['text_in_search'] : "";
    $left_items_cat = isset($requestData['left_items_cat']) ? trim($requestData['text_in_search']) : "";

    if($left_items_cat == "Companies"){
        $dataProvider = new ActiveDataProvider([
            'query' => (new \yii\db\Query())
            ->select(['c.name', 'c.id'])
            ->from(['companies as c'])
            ->where('c.name LIKE :query')
            ->addParams([':query'=>'%'.$text_in_search.'%']),
            'pagination' => [
                'pageSize' => 20,
            ],
        ]);

        return \yii\grid\GridView::widget([
            'dataProvider' => $dataProvider,
            'columns' => [
                ['class' => 'yii\grid\SerialColumn'],
                // your columns here...
                ['class' => 'yii\grid\ActionColumn'],
            ],
        ]);
    }
}

On your VIEW file you should create an area (possible element And then in your js file where you are making the AJAX request, make sure the response does something like:

function (data, textStatus, jqXHR) {           
    $("#show-grid-here").html(data); //or data[0], I'm not sure. try both.
},
查看更多
登录 后发表回答