简体   繁体   中英

Unable to post the data from view to controller in Yii2

I am working on Yii2 . I have a gridview with checkbox and on a button click I am redirecting it to an action controller using ajax.

 <?= Html::a('Disconnect', ['dco'], ['class' => 'btn btn-success', 'id'=>'dco']) ?>

<?php Pjax::begin(); ?>    
        <?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [


        ['class' => 'yii\grid\CheckboxColumn', 'checkboxOptions' => function($d) {
            return ['value' => $d['msn']];
        }],


        'ref_no',
        'dept_code:ntext',
        'dept_name:ntext',

        'allowed_units',
        'msn',

        'units_consumed',
        [
            'label' => 'Disconnected',
            'attribute' => 'disconnected',
            'format'=>'raw',
            'contentOptions' => ['style'=>'text-align:center'],
            'value' => function($model){
                return $model->disconnected == 1 ? '<span class="glyphicon glyphicon-ok text-success"></span>' : '<span class="glyphicon glyphicon-remove text-danger"></span>';
            },
            'filter' => Html::activeDropDownList($searchModel, 'disconnected', [''=>'All','1'=>'Yes','0'=>'No'], ['class' => 'form-control']),
        ],

        'diconnected_at',
        'reconnected_at',
        'active_energy_total_m',


        ['class' => 'yii\grid\ActionColumn'],
    ],
]); ?>
<?php Pjax::end(); ?>

JS

<?php

$DCOurl = Url::toRoute(['/hecolog/dco']);

$script = <<< JS
$(document).ready(function () {  



 //DCO 
 $('#dco').on('click',function(e) {


       e.preventDefault();    
 var strValue = "";        
    $('input[name="selection[]"]:checked').each(function() {

    if(strValue!=="")
        {
        strValue = strValue + " , " + this.value;

        }
    else 
       strValue = this.value;     

});       

 $.ajax({
    url: '$DCOurl',
    type: 'POST',
    dataType: 'json',
    data: {data:strValue},         
    success: function(data) {
       alert(data);
    }
 });


 });
});
JS;
$this->registerJs($script, static::POS_END);
?>

But when I click on the disconnect button it doesn't redirect to my controller. In console it gives me Not Found (#404): Page not found.

Update 1

I have updated the ajax call like below

$.ajax({
    url: $DCOurl, // removed the inverted commas ''
    type: 'POST',
    dataType: 'json',
    data: {data:strValue},         
    success: function(data) {
       alert(data);
    }
 });

Controller

 public function actionDco()
{
    if(Yii::$app->request->isAjax && Yii::$app->request->post())
    {
        $data = explode(',',$_POST['data']);

        var_dump($data);
        die();
    }
    else{
        $this->redirect('index');
    }




}

After updating the code as suggested I am able to go into my controller but still not able to get the data

In console I am getting error Uncaught SyntaxError: Invalid regular expression flags

在此输入图像描述

Update 2

Below is the code for my view

<?php

use yii\helpers\Html;
use yii\grid\GridView;
use yii\widgets\Pjax;
use yii\helpers\Url;
use yii\web\JqueryAsset;
/* @var $this yii\web\View */
/* @var $searchModel common\models\HescologSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = 'DCO / RCO';
$this->params['breadcrumbs'][] = $this->title;
?>
<section class="content-header">
<h1>DCO / RCO List</h1>
</section>
<section class="content">
<div class="box">
    <div class="box-body">


<p>

    <?= Html::a('Disconnect', ['dco'], ['class' => 'btn btn-success', 'id'=>'dco']) ?>
    <?= Html::a('Re-Disconnect', ['rco'], ['class' => 'btn btn-info','id'=>'rco']) ?>
</p>

 <?php Pjax::begin(); ?>
        <div class="pre-scrollable">
        <?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [


        ['class' => 'yii\grid\CheckboxColumn', 'checkboxOptions' => function($d) {
            return ['value' => $d['msn']];
        }],


        'ref_no',
        'dept_code:ntext',
        'dept_name:ntext',

        'allowed_units',
        'msn',

        'units_consumed',
        [
            'label' => 'Disconnected',
            'attribute' => 'disconnected',
            'format'=>'raw',
            'contentOptions' => ['style'=>'text-align:center'],
            'value' => function($model){
                return $model->disconnected == 1 ? '<span class="glyphicon glyphicon-ok text-success"></span>' : '<span class="glyphicon glyphicon-remove text-danger"></span>';
            },
            'filter' => Html::activeDropDownList($searchModel, 'disconnected', [''=>'All','1'=>'Yes','0'=>'No'], ['class' => 'form-control']),
        ],

        'diconnected_at',
        'reconnected_at',
        'active_energy_total_m',


        ['class' => 'yii\grid\ActionColumn'],
    ],
]); ?>
        </div>
<?php Pjax::end(); ?>

    </div>
</div>
</section>
<?php

$DCOurl = Url::toRoute(['/hescolog/dco']);
$RCOurl = Url::toRoute(['/hescolog/rco']);

$script = <<< JS
$(document).ready(function () {      
//DCO 
 $('#dco').on('click',function(e) {


       e.preventDefault();    
 var strValue = "";        
    $('input[name="selection[]"]:checked').each(function() {

    if(strValue!=="")
        {
        strValue = strValue + " , " + this.value;

        }
    else 
       strValue = this.value;     

});



$.ajax({
    url: $DCOurl,
    type: 'POST',
    dataType: 'json',
    data: {data:strValue},         
    success: function(data) {
       alert(data);
    }
 });


 });

 $('#rco').on('click',function(e) {

 e.preventDefault();    
 var strValue = "";        
    $('input[name="selection[]"]:checked').each(function() {

    if(strValue!=="")
        {
        strValue = strValue + " , " + this.value;

        }
    else 
       strValue = this.value;     

  });

  $.ajax({
    url: '$RCOurl',
    type: 'POST',
    dataType: 'json',
    data: {data:strValue},         
    success: function(data) {
       alert(data);
    }
 });
 });

 });    
 JS;
 $this->registerJs($script, static::POS_END);
 ?>

I must be doing something wrong which I am not understanding

Any help would be highly appreciated.

first of all url:'$DCOurl' is correct and url must be in single or double quotation. so you have a not found problem:

  • is your project in htdocs or www followed by /inventory-web/backend/ or there are some more directories? you use relative url so the url would be for ex: localhost/inventory-web/backend/web/ ...
  • ajax type 'POST' should match with behaviors['verbs']['actions'] if you have set it
  • check controller file name, class name and namespace

First, if you're serving an Ajax request you cannot do a redirect:

public function actionDco()
{
    Yii::$app->response->format = Response::FORMAT_JSON;
    $rv=[];
    if(Yii::$app->request->isAjax && Yii::$app->request->post())
    {
        $data = explode(',',$_POST['data']);

        $rv["infos"]=$data;
        $rv["status"]='gotData';
    }
    else{
        $rv["url"]=Url::to('index');
        $rv["status"]='redirect';

    }
    return $rv;
}

About the JS error, instead of:

$.ajax({
    url: $DCOurl,
    type: 'POST',
    dataType: 'json',
    data: {data:strValue},         
    success: function(data) {
       alert(data);
    }
 });

Add the quotes aroun the $DCOurl and to manage the return value from the ajax call

$.ajax({
    url: "$DCOurl",
    type: 'POST',
    dataType: 'json',
    data: {data:strValue},         
    success: function(data) {
       if(data.status=='gotData'){
           alert(data.infos);
       }
       if(data.status=='redirect'){
           window.location.href=data.url;
       }
    }
 });

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