简体   繁体   中英

How to save data using ajax request using CGridview in Yii

When I submit button to update it does not save the data.Here in my view.php file -> `

'id'=>'main-table-grid',
    'dataProvider'=>$dataProvider,
    'columns'=>array(
    array(
      'name'=>'section_no',
      'type'=>'raw',
      'value'=>'CHtml::link($data->section_no)',
    ),
        'section_name',
        'sub_sec_no',
        'sub_sec_name',
        array(
      'name'=>'text',
      'htmlOptions'=>array('width'=>'150'),
      'type'=>'raw',
      'value' => 'CHtml::textArea("MainTable[text]",$data->text)',
    ),
        'review_response',
    array(
      'name'=>'review_comment',
      'htmlOptions'=>array('width'=>'default'),
      'type'=>'raw',
      'value' => 'CHtml::textArea("MainTable[review_comment]",$data->review_comment)',
    ),
    array(
      'class' => 'CButtonColumn',
      'template' => '{update}{view}{delete}',
      'buttons' => array(
        'update' => array(
          'options' => array('class' => 'save-ajax-button'),
          'url' => 'Yii::app()->controller->createUrl("saveModel", array("id"=>$data->id))',
        ),
        'view',
        'delete',
      ),
    ),
    ),
)); 
?>
<script>
   $('#main-table-grid a.save-ajax-button').live('click', function(e)
    {
        var row = $(this).parent().parent();

        var data = $('input', row).serializeObject();

        $.ajax({
            type: 'POST',
            data: data,
            url: jQuery(this).attr('href'),
            success: function(data, textStatus, jqXHR) {
                console.log(text);
                console.log(textStatus);
                console.log(jqXHR);
            },
            error: function(textStatus, errorThrown) {
                console.log(textStatus);
                console.log(errorThrown);
            }
        });
        return false;
    });


    $.fn.serializeObject = function() {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function() {
            if (o[this.name]) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };
</script>`

and in my controller I created an action method.The code is below->

public function actionSaveModel($id) {
    $model=$this->loadModel($id);
    $this->performAjaxValidation($model);
    if(isset($_POST['MainTable']))
        {
      $model = new MainTable();
      $model->attributes = $_POST['MainTable'];
      $model->save();
      $this->render('admin', array(
         'model' => $model,
      ));
        }
  }

I have set permission in my controller

    array('allow', // allow authenticated user to perform 'create' and 'update' actions
        'actions'=>array('savemodel'),
        'users'=>array('@'),
    ),

My problem is data is not saving in the table.Please let me know what is the issue here. Thank you.

Ok now I have solved the issue.I am getting ajax response by selecting the ID which I need to update and post the data to my controller.

<script type="text/javascript">
$(function() {  
  $('#MainTable_text').live('click', function(e)
    {
        var val=this.value;
        $.ajax({
            type: 'POST',
            data: {des:val},
            url: "<?php echo $this->createUrl("maintable/save"); ?>",
            success: function(data, textStatus, jqXHR) {
                console.log(data);
                console.log(textStatus);
                console.log(jqXHR);
            },
            error: function(textStatus, errorThrown) {
                console.log(textStatus);
                console.log(errorThrown);
            }
        });
        return false;
    });
});

after that I catch the value in controller and update in database.

  public function actionSave() {
    $command = Yii::app()->db->createCommand();
    $user = $_POST['des'];
    if (isset($user)) {
      $command->update('main_table', array(
          'text' => $user,
              ), 'id=:id', array(':id' => $id));
      $this->render('save', array(
          'model' => $model,
      ));
    } else {
      echo 'error found';
    }
  }

Please put your jQuery code inside this code:

<script type="text/javascript">
$(function() {
// put your jQuery code here
});
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM