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 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝