Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
151 views
in Technique[技术] by (71.8m points)

javascript - 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' => 'yiigridCheckboxColumn', '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' => 'yiigridActionColumn'],
    ],
]); ?>
<?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

enter image description here

Update 2

Below is the code for my view

<?php

use yiihelpersHtml;
use yiigridGridView;
use yiiwidgetsPjax;
use yiihelpersUrl;
use yiiwebJqueryAsset;
/* @var $this yiiwebView */
/* @var $searchModel commonmodelsHescologSearch */
/* @var $dataProvider yiidataActiveDataProvider */

$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' => 'yiigridCheckboxColumn', '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' => 'yiigridActionColumn'],
    ],
]); ?>
        </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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...