Utilizing Bootstrap Modal to Display PHP Data Dynamically

Modals always pose a challenge for me, especially when I'm trying to work with someone else's code that has a unique take on modals that I really appreciate (if only I can make it function correctly).

The issue arises when the modal is supposed to display item-specific information based on an ID. However, upon clicking to exit and selecting the trigger for different item-specific information with a unique ID, the old information is displayed instead. It seems like the modal needs to be reset or destroyed between triggers. Here's how it should ideally work for this project:

  1. Populate Inventory Page With Database Information
  2. On Action Click, Pass Item ID to Modal
  3. Show Modal With Additional Item-Specific Information
  4. Allow Users to Close Modal and Select Another Item Action
  5. Repeat Steps 2-4 for Different Items

Here's my existing code:

inventory.php

The Trigger:

 <a data-toggle="modal" data-target="#ajax" data-id="<? echo $row['id'];?>" href="./mod/v_email.php?id=<? echo $row['id'];?>" class="btn red btn-sm dropdown-toggle inv_action">Email <i class="icon-note"></i></a>

Then, the modal initialization at the bottom of the page:

 <div class="modal fade" id="ajax" role="basic" aria-hidden="true">
     <div class="page-loading page-loading-boxed">
         <img src="../../assets/global/img/loading-spinner-grey.gif" alt="" class="loading">
         <span>
    &nbsp;&nbsp;Loading... </span>
     </div>
     <div class="modal-dialog">
         <div class="modal-content">
         </div>
     </div>
 </div>

v_email.php

 $id=($_GET['id']);

 <div class="modal-header">
    <button type="button" class="close" id="modal_close" data-dismiss="modal" aria-hidden="true"></button>
    <h4 class="modal-title">Let someone know!</h4>
</div>

<!-- Rest of your modal content and form goes here -->

In conclusion, there seems to be an issue with resetting or destroying the modal data between triggers, which is causing the incorrect information to be displayed. If you have any insights or need additional information, please feel free to comment so I can provide more details. Thank you.

Answer №1

To solve the issue of modal opening with new item detail, I recommend keeping all scripts in the `inventory.php` page and removing them from the `v_email.php` page.

You can either use:

$("#ajax").on('hidden.bs.modal', function () {
    $(this).data('bs.modal', null);
});

or

$("#ajax").on('hidden.bs.modal', function () {
    $(this).removeData('bs.modal');
});

to clear the old data from the modal.

inventory.php

HTML:

<a data-toggle="modal" data-target="#ajax" data-id="<? echo $row['id'];?>" href="./mod/v_email.php?id=<? echo $row['id'];?>" class="btn red btn-sm dropdown-toggle inv_action">Email <i class="icon-note"></i></a>
 <div class="modal fade" id="ajax" role="basic" aria-hidden="true">
     <div class="page-loading page-loading-boxed">
         <img src="../../assets/global/img/loading-spinner-grey.gif" alt="" class="loading">
         <span>
    &nbsp;&nbsp;Loading... </span>
     </div>
     <div class="modal-dialog">
         <div class="modal-content">
         </div>
     </div>
 </div>

JS:

Note: Add the following code after jQuery and Bootstrap library (jQuery & Bootstrap libraries should always come first).

Replace

$("form#veh_email_form").on("submit",function()
with
$(document).on("submit", "#veh_email_form", function ()

<script>
    $(document).ready(function(){
        $(document).on("submit", "#veh_email_form", function () {
            $('form#veh_email_form input[type=submit]').attr({disabled: 'disabled',value: 'Submitting Application ...'});
            var formData = $("form#veh_email_form").serialize();
            $.ajax({
                type: 'POST',
                url: './mod/mod_helper/veh_email_proc.php',
                data: formData,
                async: false,
                success: function(msg){
                        if((msg) == 1)  {               
                            $("#modal_close").trigger("click");
                        } 
                        else { 
                            $("#app_error").show();
                        } 
                }               
            });             
            return false;               
        });
        $("#ajax").on('hidden.bs.modal', function () {
            $(this).data('bs.modal', null);
        });
        $("#modal_close").click(function() {
            $('#ajax').removeData('modal');
        }); 
    });
</script>

v_email.php

<?php
 $id=($_GET['id']);
?>
 <div class="modal-header">
    <button type="button" class="close" id="modal_close" data-dismiss="modal" aria-hidden="true"></button>
    <h4 class="modal-title">Let someone know!</h4>
</div>
<form id="veh_email_form" method="post">
<div class="modal-body">
    <div class="row">
        <div class="col-md-6">
            <div class="input-group">
                <span class="input-group-addon">
                    <i class="fa fa-user"></i>
                </span>
                <input type="text" class="form-control" name="name" placeholder="Name" required="required">
            </div>
            <div class="input-group">
                <span class="input-group-addon">
                    <i class="fa fa-envelope"></i>
                </span>
                <input type="email" class="form-control" name="email" placeholder="Email" required="required">
            </div>
            <div class="input-group">
                <textarea class="form-control" style="width:269px;height:117px;" rows="3" name="message" placeholder="Message">
                <? echo $id;?></textarea>
            </div>
        </div>
    </div>
</div>
<div class="modal-footer">
    <input type="submit" class="btn red-haze" value="Send Email">
</div>
</form>

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

Using $i++ in this scenario helps to locate the appropriate array element's index

When the cart array is empty, it takes the item id and displays the quantity as 1. If not, it goes into a foreach loop where if the item is already in the array, array_splice will take place. The logic behind $i++ and $i-1 for offset position is how it c ...

Unlocking the validator service within a custom repository in Symfony: A step-by-step guide

I have implemented @Assert\Choice validation for a property within an entity. ApplicationQuestion.php <?php /** * ApplicationQuestion * * @ORM\Table(name="j_application_questions") * @ORM\Entity(repositoryClass="JobsBundle\Rep ...

JSON Date Format

I'm facing an issue where I am unable to retrieve the current date using new Date() because it is in JSON format. This particular code was written using MVC C#. The date appears as \/Date(1531364413000)\/. The dates stored in the database ...

Checking to see if all the users mentioned in the message have been assigned a role

Hello everyone, I'm new to asking questions here so please bear with me. I am trying to retrieve all the users mentioned in a message and check if any of them have a specific role, such as the staff role. Thank you for your help! Edit: Here is the ...

Is it possible to update the .reduce() method in React similar to how useState() is

Currently, I am immersed in a small project focusing on the "Cart" feature. The only missing piece of the puzzle at this point is calculating the total price for each product. I've managed to calculate it, but when adding multiple units of a single p ...

Adjusting webpage zoom based on different screen sizes

Hey there, I ran into an issue with my web page design. It looks great on my desktop monitors, but when I checked it on my laptop, things went haywire. Strangely, adjusting the zoom to 67% seemed to fix the problem. Both screens have a resolution of 1920 ...

Issue with res.redirect not functioning as expected

I am having some difficulty with the use of res.redirect() in my express application. After searching through other questions, I haven't found a solution that directly addresses my specific issue or is detailed enough to be useful. app.get(/\d& ...

Injecting a parameter at the end of a web address - HTML

I need to append a value to the end of an existing URL. For instance, if a user enters "hello world" into an input field, clicks submit, and should be directed to: http://google.com/?q=hello%20world Is it possible to accomplish this using only HTML or d ...

Executing shell commands via PHP in Ubuntu

I am currently running ubuntu with libreOffice. I have successfully installed unoconv to convert an *.odp file to a *.pdf. When I execute the command unoconv -f pdf myfile.odp from the terminal, everything works perfectly fine. Now, I am trying to achieve ...

Exporting variables in Angular's Ahead of Time (AoT) compiler is

I recently attempted to incorporate dynamic configuration into my project, following a guide I found in this insightful post. While everything functions smoothly with the JiT compiler, I encountered the following error when attempting to build using the A ...

How to retrieve the value of a selected radio button in an AngularJS radio button group that uses ng-repeat

In the following code snippet, I am trying to retrieve the value when any of the radio buttons is selected: <label ng-repeat="SurveyType in SurveyTypes"> <input type="radio" name="SurveyTypeName" ng-model="surveyData.SurveyTypeN ...

Validate the checkbox with Vuelidate only when the specified property is set to true

I have a website login form where users may need to check a specific checkbox before logging in. Here is part of the Vue component code that handles this functionality: <script setup lang="ts"> import {ref, defineProps} from 'vue&a ...

The PureComponent FlatList does not refresh properly even after including extraData={this.state} as a prop

After conducting some research, I discovered that using a PureComponent instead of a regular Component can enhance the performance of my FlatList. By doing so, only the row that was changed will be re-rendered rather than the entire list. However, I encoun ...

Show a particular tier of a hierarchy within a category structure on WordPress

Is there a way to show only a specific category level of a post? Imagine this scenario: I have a post with categories structured hierarchically as follows... Parent cat -Child cat A --Child cat B ---Child cat C I need a clever snippet of code to inse ...

Using React to Retrieve Array Data from an API and Implementing Filtering

I have successfully made a call to my API endpoint and passed the token. However, I only need specific details from the response data - specifically, I want to work with the first index in the array that contains fields. My goal is to fetch all the relevan ...

Highcharts - resolving cross-browser e.Offset discrepancies in mouse event detection on charts

I need to determine if the mouseup event is inside the chart and display the coordinates of the point. The code works in Chrome but not in Firefox due to the lack of the event.offset property. jQuery(chart.container).mouseup(function (event) { eoff ...

Uploading Files Using CodeIgniter's User Class

I am in a bit of a bind. I have a User Class that includes an edit_profile() function, and I would like to enable users to upload their photo while editing their profile. The issue is, when the form is submitted, it remains on the edit profile page utilizi ...

Can I access properties from the index.html file within the Vue.js mount element?

<!DOCTYPE html> <html lang=""> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="widt ...

I am experiencing issues with my INSERT INTO statement

I've been working on creating a news system that allows users to fill out a form to post an article. However, despite multiple attempts and methods, my INSERT INTO query doesn't seem to be functioning properly. I have two separate files for this ...

Retrieve an object that includes a property with an array of objects by filtering it with an array of strings

I have a large JSON file filled with data on over 300 different types of drinks, including their ingredients, names, and instructions. Each object in the file represents a unique drink recipe. Here is an example of how one of these objects is structured: ...