weixin_33671935 2016-10-28 09:57 采纳率: 0%
浏览 32

在Yii2上使用Ajax进行全日历

I'm using Fullcalendar for Yii2 (https://github.com/philippfrenzel/yii2fullcalendar-demo) and I want to save with Ajax the event when I click on a date. The datas commes from the dropdownlist.

It seems that my code couldn't find the function in my controller, maybe it's the Url ?

My view with JS and the link to my funstion Ajax on my controller :

<?php 
        $form = ActiveForm::begin(); 
    ?>

    <div class="row">
        <div class="col-md-4">
            <?= $form->field($feuille_de_jour_responsable, 'ID_Categorie')->dropDownList(CategorieFdj::find()->select(['Nom', 'ID_Categorie'])->indexBy('ID_Categorie')->column(), ['id'=>'catId']); ?>
        </div>
        <div class="col-md-4">
            <?= $form->field($feuille_de_jour_responsable, 'ID_Poste_FDJ')->dropDownList(PosteFdj::find()->select(['Nom_Poste_FDJ', 'ID_Poste_FDJ'])->indexBy('ID_Poste_FDJ')->column(), ['id'=>'postId']); ?>
        </div>
        <div class="col-md-4">
            <?= $form->field($feuille_de_jour_responsable, 'Code_Personnel')->dropDownList(Personnel::find()->select(['Nom_Personnel', 'Code_Personnel'])->indexBy('Code_Personnel')->column(), ['id'=>'codePers']); ?>
        </div>
    </div>


    <?php ActiveForm::end();?>



<?php 
    $JSCode = <<<EOF

    function(start,end) {
        //alert ($("select[id=catid] option:selected").text());
        var title = $("select[id=codePers] option:selected");
        var codePersonnel = $("select[id=codePers] option:selected").val();
        var posteId = $("select[id=postId] option:selected").val();
        var categorieID = $("select[id=catId] option:selected").val();
        //alert($('#catid').val());
        var eventData;
var obj = { 
                    Date_Calendaire : start.format(),
                    ID_Poste_FDJ : posteId,
                    ID_Categorie : categorieId,
                    Code_Personnel : codePersonnel
                    };
$.ajax({
                url : 'index.php?r=feuille-de-jour-responsable/create',
                dataType: 'json',
                data: obj,
                success: function (data, response, event, date) {
                    alert("success here");
                    /*$('#calendar').fullCalendar('renderEvent',
                    {
                        title: title,
                        start: start.format()
                        //end: thedate1
                    }, true);
                    eventData = {
                        title: title,
                        start: start.format(),
                        end: start.format(),
                    };
                    $('#calendar').fullCalendar('renderEvent', eventData, true);*/
                },
                error: function () {
                    alert("Oops! Something didn't work");
                }
            });
}

EOF;

$JSEventClick = <<<EOF
function(calEvent, jsEvent, view) {
    alert('Event: ' + calEvent.title);
    alert('Coordinates: ' + jsEvent.pageX + ',' + jsEvent.pageY);
    alert('View: ' + view.name);
    // change the border color just for fun
    //$(this).css('border-color', 'red');
}
EOF;


?>

    <?= yii2fullcalendar\yii2fullcalendar::widget([
        'id' => 'calendar',
        'clientOptions' => [
            'height' => 650,
           // 'language' => 'fa',
            //'eventLimit' => TRUE,
            'selectable' => true,
            'selectHelper' => true,
            'droppable' => true,
            'editable' => true,
//          'theme'=>true,
            'fixedWeekCount' => false,
            'defaultDate' => date('Y-m-d'),
            'eventClick' => new JsExpression($JSEventClick),
            'select'=>new JsExpression($JSCode)
        ],            

    ]);
?>

    <?= Html::encode($JSCode); ?> 

    <?= Html::encode($JSEventClick); ?>

And the function on my controller (FeuilleDeJourResponsableController)

        public function actionCreate()
{

     $feuille_de_jour_responsable = new FeuilleDeJourResponsable();

    if ($feuille_de_jour_responsable->load(Yii::$app->request->post()) && $feuille_de_jour_responsable->save()) {
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        //return $this->redirect(['view', 'Date_Calendaire' => $feuille_de_jour_responsable->Date_Calendaire, 'ID_Poste_FDJ' => $feuille_de_jour_responsable->ID_Poste_FDJ, 'ID_Categorie' => $feuille_de_jour_responsable->ID_Categorie, 'Code_Personnel' => $feuille_de_jour_responsable->Code_Personnel]);
        return ['success' => $feuille_de_jour_responsable->save()];
    } else {
        return $this->render('create', [
            'feuille_de_jour_responsable' => $feuille_de_jour_responsable,
        ]);
    }
  }

I begin to use firebug and when I click, It isn't saved... No error. I was thinking in view of the link with "POST" (that is the same that a "normal" link from a form) that my function "create" will save the data but nothing happends. The "if" didn't work, I don't know why.

firebug

And I find the exception : "SyntaxError: unexpected token < in JSON in position 0"

Thank you for help =) Sarah

  • 写回答

1条回答 默认 最新

  • weixin_33690367 2016-11-13 11:23
    关注

    The return value for failed save operation is not quite valid in your case.

    if ($feuille_de_jour_responsable->load(Yii::$app->request->post()) && $feuille_de_jour_responsable->save()) {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        return ['success' => $feuille_de_jour_responsable->save()];
    } else {
        return $this->render('create', [
            'feuille_de_jour_responsable' => $feuille_de_jour_responsable,
        ]);
    }
    

    You need to return in JSON format your saving results but not page's HTML code. Since you're attempting to display entire HTML content, you're getting that SyntaxError: unexpected token < in JSON in position 0.

    For successful operation:

    return ['success' => true];
    

    By the way, you can't use $feuille_de_jour_responsable->save() again in return response as it will attempt to save twice.

    For failed operation:

    return ['success' => false];
    

    You cannot use render because that's a whole page and you're using Ajax request.

    评论

报告相同问题?

悬赏问题

  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建