Leveraging Ajax with Yii2 for enhanced functionality on the fullcalendar

I'm currently utilizing Fullcalendar for Yii2 and I am looking to save events via Ajax when clicking on a date. The data comes from a dropdown list.

It seems like my code is unable to locate the function in my controller, possibly due to the URL?

Here is my view with JavaScript along with the link to my Ajax function in the 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

    // JavaScript code goes here...

EOF;

$JSEventClick = <<<EOF
function(calEvent, jsEvent, view) {
    alert('Event: ' + calEvent.title);
}
EOF;

?>

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

    ]);
?>

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

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

And here's the function in my controller (FeuilleDeJourResponsableController)

        public function actionCreate()
{
     // PHP code for creating an event...
}

When using firebug, I noticed that upon clicking, nothing gets saved without any errors appearing. I assumed that by linking "POST" (similar to submitting a form), my "create" function would save the data, but it remains unsuccessful. The "if" statement doesn't execute, and I'm unsure why.

firebug

An exception was found stating: "SyntaxError: unexpected token < in JSON at position 0"

Any help or guidance would be greatly appreciated! Sarah

Answer №1

Your situation does not quite align with the expected return value for a failed save operation.

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,
    ]);
}

To handle saving results in JSON format instead of HTML, adjust your code accordingly to avoid the

SyntaxError: unexpected token < in JSON in position 0
caused by returning HTML content.

If the operation is successful:

return ['success' => true];

Note that using

$feuille_de_jour_responsable->save()
again in the response can lead to unintended consequences by attempting to save data twice.

In case of a failed operation:

return ['success' => false];

Avoid using render as it generates a full page response, which is inappropriate for an Ajax request.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

jQuery failing to append code after being removed

I need some assistance with an issue I've run into while using jQuery's .remove(). Here is a snippet of code that showcases the problem: $( '.video-button span.glyphicon-play' ).click(function() { $( '#video-player' ).ap ...

Arranging functions in descending and ascending order

I am working on a Table component that has an array of columns and data. I need to sort the columns and update the table state accordingly. My method takes two arguments key (column key) and sortable (true or false indicating if the column is sortable or ...

Is it necessary to validate when invoking a partial view using ajax?

public PersonViewModel() { Children = new List<ChildViewModel>(); } [Required(ErrorMessage = "Required!")] public string FName { get; set; } [Required(ErrorMessage = "Required!")] public string LName { get; set; } ...

What is the easiest way to access an array using its name?

I have 2 arrays like this: var windows_array = []; var google_array = []; I am looking to access a specified array in a function by passing the network as a parameter. function add_friends(network, friend){ (network + '_array').push(friend ...

Regular expression is used to limit input to integers only, specifically numbers between -130 and 30

Completed the regex for 0 to 50 ^(?:[1-9]|[1-4][0-9]|50)$ The current regex is functioning correctly. Next step is to create a regex that includes negative numbers, allowing for values between -130 and 30 without any decimal points. ...

Exploring the efficacy of unit testing on Express controllers

After days of working on this, I've hit a wall and finally decided to ask for assistance. Everything runs smoothly when the server is up and API calls are made. However, when attempting to unit test the controller, I encounter some issues. I'm ...

Observing input value in Popover Template with Angular UI

I am currently working on a directive that utilizes the Angular Bootstrap Popover and includes an input field. Everything seems to be functioning properly, except for the fact that the watch function is not being triggered. For reference, you can view the ...

Opt for a submit <button> over an <input> button option

Is it possible to submit a form using <button> instead of <input>? I understand that a <button> cannot handle the form submission like a <input>, and I need to use the onclick method. I have attempted various solutions, but none se ...

Calling Ajax inside each iteration loop

I have encountered numerous posts discussing this topic, but the solutions I came across do not quite suit my needs. Some experts suggest changing the code structure, however, I am unsure of how to go about doing that. What I desire: 1) Retrieve a list ...

capturing images of web elements and a three-dimensional scene created with Three.js

Is there a way to capture and save a screenshot of a page that includes all HTML content as well as a Three.js scene? I've tried using html2canvas, but it only captures HTML elements. I also attempted to use the following code to take a snapshot of th ...

Substitute dynamic Angular expressions with fixed values within a string

Inside my angular controller, I am defining a stringTemplate containing expressions like "{{data.a}} - {{data.b}}". Along with that, I have an object named data with values {a: "example1", b: "example2"}. My goal is to find a way to replace the dynamic ex ...

Transferring information to a partial view using a jQuery click event

In my Index view, there is a list of links each with an ID. My goal is to have a jQueryUI dialog box open and display the ID when one of these links is clicked. Currently, I am attempting to use a partial view for the content of the dialog box in order to ...

Ways to set values for attributes

I am seeking guidance on how to set values for the properties foo and greetingMessage App.vue: <template> <img alt="Vue logo" src="./assets/logo.png"> <HelloWorld msg="Welcome to Your Vue.js App"/> < ...

Toggle among 10 divs, but automatically revert back to the initial div if there is no mouse activity for a short period

My website has 9 links in the header and 10 divs in the body. The first div serves as the main page, while the remaining 9 divs contain different content. I would like to implement a feature where when users hover over the 9 links, it displays one of the 9 ...

Ways to display tinyMCE content in a unique manner

I've been diving into node.js/express/mongoDB and decided to create a blog. I encountered an issue with rendering the content inputted through tinyMCE as HTML - instead, it's displaying the tags around my content. How can I properly display it as ...

Functionality not functioning within Shadow DOM

After creating and exporting an Angular Element as a single script tag (user-poll.js), using the element on a host site is simple. Just include the following two lines: <user-poll></user-poll> <script src="path/to/user-poll.js"></sc ...

Encountered Runtime Error: TypeError - Carousel triggering issue with reading properties of null (specifically 'classList') in Tailwind Elements

Currently, I am encountering the error message: Unhandled Runtime Error TypeError: Cannot read properties of null (reading 'classList') while utilizing the Carousel component. The problem arises when I attempt to populate the carousel with images ...

Prevent Click Event in JQuery

I have a requirement to disable all click events on my webpage. However, even after using the appropriate code to prevent these events from firing, some of them are still getting called. Let me explain with an example. <div id='parent'> ...

Error encountered when trying to access JSON data using jQuery due to a formatting issue

I encountered an issue with accessing and storing the contents of a JSON file into an array. Despite everything seeming to function correctly, I am receiving an error in the console when using Firefox. Not Well Formed. The error points to my JSON file. H ...

What is preventing me from setting flex when I add display flex to the parent element?

Currently, I am developing components in React and experimenting with styling using index.css (although I understand this is not the recommended approach). Below is the current structure: https://i.sstatic.net/8euhM.png I am looking to display a specific ...