Guide for displaying retrieved information on a Bootstrap Modal window following data submission in Yii2

I'm encountering an issue with a Modal popup that contains two fields. The first field is used to submit information and perform an internal database query, while the second field should display the returned data. Oddly enough, when testing the functionality of these fields independently (not within a Modal), everything works smoothly. However, when tested within the Modal, only the data submission occurs without displaying any results on the same Modal. What could be causing this discrepancy? Thank you for your help.

The following code snippet shows how the Modal popup is triggered:

<?php Pjax::begin() ?>
        <p>
        <?= Html::button('Quick Search', ['value' =>Url::to('index.php?r=site/mypopup'),'class' =>'btn btn-success', 'id'=>'modalButton']) ?>
        </p>
        <?php
        Modal::begin([
        'header'=> '<h4>My Modal Popup</h4>',  
        'id' => 'modal',
        'size' => 'modal-lg',
        ]);
        echo "<div id='modalContent'></div>";
        Modal::end();
<?php Pjax::end(); ?> 

This corresponds to the view for the mypopup feature:

<?php Pjax::begin(['enablePushState' => false]); ?>

            <?php $form = ActiveForm::begin(['id' => 'mypopup-form', 'options' => ['data-pjax' => true],]); ?>

                <?= $form->field($model, 'pattern')->textArea(['rows' => 1]) ?>

                <div class="form-group">
                    <?= Html::submitButton('Submit', ['class' => 'btn btn-primary', 'name' => 'mypopup-button']) ?>
                </div>
                <?php
                     echo "<pre>";
                     //SECOND FIELD
                     print_r($model->data); 
                ?>
            <?php ActiveForm::end(); ?>
            <?php Pjax::end(); ?> 

Shown below is the controller function for mypopup:

public function actionMypopup()
    {

            $model = new PopupForm();

            if ($model->load(Yii::$app->request->post()) && $model->validate()) {

                    $model->insertPopup();
                 return $this->renderAjax('mypopup', ['model' => $model]);

            } else {
                return $this->renderAjax('mypopup', ['model' => $model]);
            }   
    } 

Lastly, here is the corresponding JavaScript file used in the implementation:

$(function(){

    $('#modalButton').on('click', function(){
            $('#modal').modal('show')
                .find('#modalContent')
                .load($(this).attr('value'));
            }); 

        $(document).ajaxComplete(function (event, xhr, settings) {
         alert(xhr.getResponseHeader());
     });

});

Answer №1

To solve the issue, I made changes in two parts:

Firstly, I implemented a jQuery beforeSubmit function in the main.js file to prevent page refresh and submit the form using ajax.

This new code snippet should be placed below the existing code in the js file.

$('body').on('beforeSubmit', 'form#mypopup-form', function() {
    var form = $(this);
    if (form.find('.has-error').length) {
      return false;
    }

    $.ajax({
      url: form.attr('action'),
      type: 'post',
      data: form.serialize(),
      success: function(data) {
        $(form).find('.results').html(data);

    return false;
  });
           }
    });

Secondly, I triggered the ajax call to the form action, and in the view, I added a condition to verify if data is being posted through ajax and then display the results in a div called "results".

This second piece of code needs to be inserted above all other code in the mypopup file:

<?php 
if(isset($_POST['MyPopupForm'])) {
    echo "<pre>";
    print_r($model->data); 
    echo '</pre>';
    exit();
}
?>

Finally, towards the end of the same file, add the following:

<div class="results"></div>

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

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

The marriage of Vue 2.0 and Rails 5: Shifting from Reactive to Declarative Rendering

As I make my way through the Vue guide with a Rails 5 app, I've noticed that although I am able to update my Vue js object, the DOM doesn't behave as described in the Declarative Rendering section. The data and the DOM are supposed to be linke ...

Vue - Error Message from Eslint Regarding Absence of Variable in Setup Function

Interestingly, the Vue.js documentation strongly recommends using the <script setup> syntax of the Composition API. The issue with this recommendation is that the documentation lacks depth and it conflicts with other tools (like eslint). Here is an e ...

best way to eliminate empty p tags and non-breaking spaces from html code in react-native

How can I clean up dynamic HTML content by removing empty <p> tags and &nbsp? The whitespace they create is unwanted and I want to get rid of it. Here's the HTML content retrieved from an API response. I'm using the react-native-render ...

Developing modular applications with Vue.js and leveraging locally installed NPM packages

I am currently working on developing a modular application using Vue through the vue-cli-service. The main application and its modules are located in separate folders, with a structure that looks something like this: -- app/package.json /src/** -- mo ...

Initiate a fresh start with an automatic input reset

When you perform an action in the first id = "benodigheden", I believe there should be a specific outcome that then triggers a second rule for id = "benodigheden". However, I have been unsuccessful in finding information on this topic online. It seems like ...

Having trouble executing a jQuery function within AJAX-generated code

I may not be very experienced in JavaScript programming, but I am learning and trying my best to improve. Please excuse any errors I make along the way. Currently, I am attempting to use Ajax (not jQuery ajax) to save customer details, which then returns ...

Customizing React-Data-Grid styles using Material-UI in a React application

Imagine a scenario where we have a file containing themes: themes.js: import {createMuiTheme} from "@material-ui/core/styles"; export const myTheme = createMuiTheme({ palette: { text: { color: "#545F66", }, }, }); In ...

The meshes in my Unity game appear flipped after I import them from 3ds Max with skinning applied

After bringing my meshes from 3ds MAX to Unity with skinning, I've noticed that they appear inverted in-game. Both the mesh and normals seem to be reversed, giving them an eerie, ghost-like appearance. Interestingly, disabling the skin option resolv ...

How to Retrieve the Access Token from Instagram using Angular 2/4/5 API

I have integrated Instagram authentication into my Angular 2 project using the following steps: Begin by registering an Instagram Client and adding a sandbox user (as a prerequisite) Within signup.html, include the following code snippet: <button t ...

What steps do I need to take to implement a "single-instance" feature on my ASP.Net AJAX web portal?

Recently, a question came up regarding the possibility of "single-instancing" our web portal. For more information on this concept in a WinForms app, you can refer to this post on Hanselman's blog. Imagine having 2 shortcuts on the same client machin ...

Parent window login portal

I have just started learning how to program web applications, so I am not familiar with all the technical terms yet. I want to create a login window that behaves like this: When a user clicks on the Login button, a window should pop up on the same page t ...

What could be causing the Twitter Timeline to fail to load based on a variable in a Vue.js component?

My goal is to display the Twitter timeline of multiple accounts based on the route. I initially attempted to use a plugin called vue-tweet-embed, but encountered issues with it. As a result, I resorted to the traditional method by embedding twitter's ...

Transform text that represents a numerical value in any base into an actual number

Looking to convert a base36 string back to a double value. The original double is 0.3128540377812142. When converting it to base 36: (0.3128540377812142).toString(36); The results are : Chrome: 0.b9ginb6s73gd1bfel7npv0wwmi Firefox: 0.b9ginb6s73e Now, h ...

Displaying a loading indicator while a file is downloading and the page is being

Is there a way to show a loading indicator while a PDF is being generated in PHP? I redirect to a separate page for the PDF generation process, but the original page stays open and simply downloads the file once it's ready. How can I make a loading in ...

Cannot seem to get my AJAX code working correctly to show comments

Having some trouble with my comment system code. The PHP part is working fine, comments are being inserted into the table without any issues. However, I am struggling with the Ajax part. The comments are not being displayed unless the page is reloaded. C ...

Submit form using jQuery after making an AJAX request with jQuery's $

I'm working on the following code: $.get(link, function(data, status) { document.getElementById("test").value = data; }); $('#formtest').submit(); Everything works fine in Firefox, but in Google Chrome the submit is done before t ...

Invoke a function immediately after the application has finished loading (using both jQuery mobile and PhoneGap)

Currently, I am facing an issue with my application (built with jQuery-mobile and Phonegap). The problem lies in the need to execute a function that makes an ajax call returning a URL of an image. After receiving the JSON response containing the URL, I wa ...

Using webpack to bundle node_modules into your application

I am facing an issue while trying to load some modules like: moment echarts In my package.json file, I have the following versions specified: "echarts": "^3.1.10" "moment": "^2.14.1" However, I am encountering the errors below: VM2282:1 Uncaught Ref ...

A div containing a form, with the form being visually integrated within the div

Hi everyone, this is my first post here and I've tried to search extensively before asking this question. I've attempted to use the following examples without success: jquery submit form and then show results in an existing div Form submit ...

What is the best way to eliminate leading and trailing spaces from a text input?

I'm currently working on troubleshooting a bug in an AngularJS application that involves multiple forms for submitting data. One of the issues I encountered is that every text box in the forms is allowing and saving leading and trailing white spaces ...