简体   繁体   中英

Ajax on Yii2 for fullcalendar

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

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.

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