Pass PHP variable to bootstrap modal

Pass PHP variable to bootstrap modal

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Pass PHP Variable to Bootstrap Modal

You are building a dynamic table where each row triggers a modal, passing a unique record ID via an HTML attribute: data-id. This is standard Bootstrap behavior. The challenge isn't generating the button; it's retrieving that specific ID once the modal opens so your server-side script can execute a targeted query. The core issue with your current setup is that PHP code runs only when the page loads. Once the HTML is sent to the browser, the variable $row['ID'] no longer exists in the client context. You cannot simply store it in a hidden input field inside the modal template because that same modal structure repeats for every row, and you need to capture the specific ID clicked.

The solution relies on JavaScript event delegation or direct event handling to bridge the gap between the static HTML and your data retrieval logic. When a user clicks the "Edit" button, Bootstrap triggers a click event. You can intercept this event, read the data-id attribute from the clicked element, and inject that value into the modal's body before displaying it.

Here is how to implement this cleanly without duplicating JavaScript code for every single row:

<!-- The Button in your Loop -->
<a href="#myModal" class="btn btn-default btn-small" 
   data-toggle="modal" 
   data-target="#myModal" 
   data-id="<?php echo htmlspecialchars($row['ID']); ?>">
    Edit
</a>

<!-- The Modal Structure -->
<div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title">Edit Data</h4>
            </div>
            <div class="modal-body" id="modalContentArea">
                <!-- Content will be injected here -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    // Event delegation handles clicks on buttons with the specific class, 
    // regardless of where they appear in the DOM.
    $('#myModal').on('show.bs.modal', function (event) {
        var trigger = $(event.relatedTarget) // The element that triggered the modal
        
        // Retrieve data-id from the button
        var id = trigger.attr('data-id')
        
        // Optional: Validate if ID was passed. If not, handle gracefully.
        if (!id) {
            return; 
        }

        // Fetch the record from your database
        $.ajax({
            url: 'load_record.php', // Your endpoint that handles the query
            type: 'GET',
            data: { id: id },
            success: function (data) {
                $('#modalContentArea').html(data); // Inject HTML or JSON into modal body
            },
            error: function() {
                $('#modalContentArea').html('Error loading record.');
            }
        });

        var modal = $(this)
        
        // Optional: Store the ID in a variable for your PHP script to use later if needed
        // This is usually handled on the server side via the AJAX response, 
        // but if you must pass it back to PHP immediately, you can do so via form submission logic.
    });
});
</script>

Why Event Delegation?

Using event delegation (binding the event listener to #myModal rather than every button) is more efficient and maintainable. Since your table is generated inside a while loop, you could end up with dozens of buttons. Attaching an individual click listener to each one would create unnecessary overhead. By listening to the modal's show.bs.modal event (a built-in Bootstrap event), you ensure that the code runs exactly once per modal open, capturing the specific ID from the element that triggered the action.

Handling Server-Side Data

In your original question, you mentioned wanting to "save the id in a variable here so i can use it in a php script." It is important to distinguish between client-side variables and server-side processing. The ID is now available as a JavaScript variable (id) inside the success callback of the AJAX call. If your PHP script expects data via a form submission, you would typically populate a hidden input field within the modal body with this ID before allowing the user to save changes.

However, if you are simply fetching data to display it immediately upon opening the modal (as shown in the AJAX example), the "PHP script" is effectively running on the server side at the moment of the request, not stored in a global variable accessible directly from the HTML. This separation of concerns keeps your code secure and prevents exposing raw PHP variables in the client environment.

Security Considerations

Always sanitize data before outputting it to the page. In the button generation loop, use htmlspecialchars($row['ID']) to prevent XSS attacks if the ID contains special characters. On the server side receiving the AJAX request, validate that the received id is an integer and matches a valid record in your database before running any queries or updating records.

Our network