Is it possible to retrieve information from a MySQL database by utilizing Bootstrap and Ajax with the selected ID?

I am currently working on two php pages. The first php page contains a table with records that can be edited using a Bootstrap Modal, while the second php page processes updates to the MySQL database.

Below is the code for the first php page (edit_account.php)

<?php
$cn = mysqli_connect("localhost","root","","testdb");
$sql = "SELECT * FROM tblinfo";
$qry = mysqli_query($cn,$sql);
$nrows = mysqli_num_rows($qry);
if ($nrows > 0) {
    while ($rows = mysqli_fetch_array($qry)) {
        $id = $rows['userid'];
        $fn = $rows['fullname'];
?>
        <tr>
            <td><?php echo $id; ?></td>
            <td><?php echo $fn; ?></td>
            <td><a href = "#edit<?php echo $id; ?>" data-toggle = "modal" class = "btn btn-success btn-sm">Edit</a></td>
        </tr>

        <div class = "modal" id = "edit<?php echo $id; ?>">
            <div class = "modal-dialog">
                <div class = "modal-content">
                    <div class = "modal-header">
                        <h5 class = "modal-title">Edit Information</h5>
                        <button class = "close" data-dismiss = "modal">&times;</button>
                    </div>
                    <div class = "modal-body">
                        <input type = "text" id = "user_id" value = "<?php echo $id; ?>" class = "form-control" />
                        <input type = "text" id = "full_name" value = "<?php echo $fn; ?>" class = "form-control" />
                    </div>
                    <div class = "modal-footer">
                        <button class = "btn btn-primary btn-sm" id = "update<?php echo $id; ?>">Update</button>
                        <button class = "btn btn-danger btn-sm" data-dismiss = "modal">Close</button>
                    </div>
                </div>
            </div>
        </div>

        <script>
            $("#update<?php echo $id; ?>").click(function() {
                var id = $("#user_id").val();
                var fn = $("#full_name").val();
                if (confirm("Are you sure you want update this record?")) {
                    $.ajax({
                        url: "edit_account_process.php",
                        type: "POST",
                        data: {
                            userid: id,
                            fullname: fn
                        },
                        success: function(data) {
                            $("#showData").html(data);
                        }
                    });
                }
            });
        </script>                       
 <?php      

    }
}
 ?>

Second php page (edit_account_process.php): This page will handle the updating of records

<?php
$cn = mysqli_connect("localhost","root","","testdb");
$id = $_POST['userid'];
$fn = $_POST['fullname'];

//for Testing
echo $id . " " . $fn;

$sql = "UPDATE tblinfo SET fullname = '$fn' WHERE userid = '$id' ";
$result = mysqli_query($cn,$sql);

if ($result) {
    echo "<script>alert('Successfully updated!');</script>";
}
else {
    echo "<script>alert('Unable to update the record!');</script>";
}
?>

I'm facing an issue where my code always selects the first record in the database even when I try to select others. Can anyone suggest how I can target a specific ID for updating?

Thanks in advance!

Answer №1

Avoid creating multiple modals and scripts for each loop iteration. Instead, create a single modal that dynamically receives values and one script to handle button clicks.

Retrieve data from data-* attributes when the button is clicked. Then, populate the input fields of your modal with these values.

<?php
$cn = mysqli_connect("localhost","root","","testdb");
$sql = "SELECT * FROM tblinfo";
$qry = mysqli_query($cn,$sql);
$nrows = mysqli_num_rows($qry);
if ($nrows > 0) {
    while ($rows = mysqli_fetch_array($qry)) {
        $id = $rows['userid'];
        $fn = $rows['fullname'];
        ?>
        <tr>
            <td><?php echo $id; ?></td>
            <td><?php echo $fn; ?></td>
            <td><a href="#" class="btn btn-success btn-sm toggleEditModal" data-uid="<?php echo $id; ?>" data-fullname="<?php echo $fn; ?>">Edit</a></td>
        </tr>                  
        <?php      
    }
}
?>

<script>
    $(".toggleEditModal").on("click", function(e) {
        e.preventDefault();
        $('#user_id').val($(this).data('uid'));
        $('#full_name').val($(this).data('fullname'));
        $("#editModal").modal('show');
    });

    $("#updateUser").click(function() {
        var id = $("#user_id").val();
        var fn = $("#full_name").val();
        if (confirm("Are you sure you want update this record?")) {
            $.ajax({
                url: "edit_account_process.php",
                type: "POST",
                data: {
                    userid: id,
                    fullname: fn
                },
                success: function(data) {
                    $("#showData").html(data);
                    $("#editModal").modal('hide');
                }
            });
        }
    });
</script>     

<div class = "modal" id = "editModal">
    <div class = "modal-dialog">
        <div class = "modal-content">
            <div class = "modal-header">
                <h5 class = "modal-title">Edit Information</h5>
                <button class = "close" data-dismiss = "modal">&times;</button>
            </div>
            <div class = "modal-body">
                <input type = "text" id = "user_id" value = "" class = "form-control" />
                <input type = "text" id = "full_name" value = "" class = "form-control" />
            </div>
            <div class = "modal-footer">
                <button class = "btn btn-primary btn-sm" id = "updateUser">Update</button>
                <button class = "btn btn-danger btn-sm" data-dismiss = "modal">Close</button>
            </div>
        </div>
    </div>
</div>

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

Encountering a 404 Error When Accessing an Express.js Route with Parameters from the Client

I've set up a server route like this: (https://github.com/leptone/lang-exchange-react/blob/master/server.js) app.route('user/:username') .get((req, res) => { console.log(req.params.username) db.findOne({ username: req.pa ...

Automate the removal of a designated shipping method in WooCommerce through programming

I need a solution to hide UPS shipping options on the cart and checkout pages when the total weight of items in the cart exceeds 150lbs. Here is my proposed code snippet: function disable_ups_shipping_over_onefifty($available_methods){ global $ ...

Is there a way for me to determine which events are linked to an object?

I am currently utilizing jqGrid for displaying read-only data from http://www.trirand.com/blog/. However, the resizable columns are causing issues with other draggable elements on the page, as they tend to get stuck when dragged over the column resize area ...

I'm having trouble with my bootstrap dropdown and I've exhausted all of my options trying to fix it based on my current understanding

My dropdown menu is not working despite adding all necessary Bootstrap CDN and files along with the jQuery script. Even with the table being handled by JavaScript, the button does not respond when clicked repeatedly. I suspect the issue lies within the han ...

Using Partial Views in ASP Core to Make Ajax Requests

Having a requirement to divide sections of a single page into Partial Views, one of which includes a form for submitting data. After some experimentation, I have successfully implemented a form submission without the need to reload the page. Yet, I am enc ...

Discover the country linked to a city using Rails and ajax in real time for an autocomplete feature

Looking for a way to implement an autocomplete feature using AJAX in a textfield. User types their city The system searches for the closest match in the database as they type Once a partially matching city is found, it displays options in the format "cit ...

How to Stop Element Flickering While Hovering in Selenium IE Webdriver

My code is functioning perfectly in Firefox, but when I try it on Internet Explorer, there is flickering. Here is my code: WebElement mouseOver= driver.findElement(By.linkText("abc")); //I'm locating the element by link text. Selenium finds the ...

Leveraging the power of jQuery with AJAX operations

In my collection of PHP files, I have three named: index page books user Index Page <link href="colorbox.css" type="text/css" rel="stylesheet" media="all" /> <script type="text/javascript" src="jquery-1.8.2.min.js"></script> <scrip ...

How can I dynamically update the status displayed in a DIV tag using PHP code?

I'm working on a web page where I am downloading data one by one in a continuous loop. Once each download is complete, I need to update the status displayed in a DIV tag on the webpage. The server connection and data download are handled by PHP code, ...

Tips for establishing a connection between two articulate models

I am handling two Models: Users and Appointments class Appointments extends Model { use HasFactory; protected $fillable = [ 'business_id', 'user_id', 'subject', 'description', ...

"What's the best way to update the src attribute of an iFrame when a user clicks

I'm new to coding in PHP or JavaScript, so please bear with me if my question isn't quite right. I'm looking for a way to dynamically pass and embed a URL from a link into the src attribute of an iframe. Essentially, I want users to click o ...

Is there a way to determine the color of an element when it is in a hover state?

I recently started using the Chosen plugin and noticed that the color for the :hover on the <li> elements is a bright blue. I want to change it to a bold red color instead. https://i.stack.imgur.com/mcdHY.png After inspecting it with the Chrome too ...

When I request the value of a JavaScript object, I am met with 'undefined'

I have been working on creating a Google map application that involves loading markers from a database and displaying them on a map. To accomplish this, I decided to create an array and define an object as shown below: function shop_info(name, latitude, l ...

Ensure the form is validated using AngularJS along with an Ajax request

I need help with HTML code <input type="text" name="username"> <label for=""> Email </label> <input type="email" name="email"> My goal is to use AJAX to check if the username and email already exist in the database ...

Design a Hover Mega Menu - click outside to close

Although there are similar topics on stackoverflow, the code I have is different from them. I am trying to achieve the following: If I click on the search box (the white square on the site), my search box should open If I open the search box and then cl ...

What's the best way to use JavaScript to obtain the width of a 'css-pixel' based on a media query?

While there have been discussions on how to determine device sizes using media queries like Twitter Bootstrap, I am looking for a reliable way to achieve the same output using JavaScript. Specifically, I want to get the CSS media query pixel number rather ...

Ensuring jQuery ajax requests can still be made when clicking on various links

After successfully creating code for ajax requests and fetching information from the server, I encountered an issue where clicking a link would smoothly transition me to a new page without refreshing the header and footer. However, upon clicking another li ...

redirecting from an AJAX request

Seeking a way to perform a redirect following an ajax `put` request. My intention is to implement client-side validation using pure JS. Client: $(document).ready(function() { login = () => { var username = $("[name='username']"). ...

Version 3.1 or higher of Django is required along with the use of the `is_ajax

HttpRequest.is_ajax() has been deprecated since the release of version 3.1. I am looking to serve HTML content when the page is accessed from a browser, and return JsonResponse when called from JavaScript or programmatically. I need advice on how to achi ...

Placing a new item following the child of a different element

How can I use jQuery to add a div inside id123 after sth2, but only for one specific occurrence? I understand how to do it after every sth2, but not just once. <div class="id123"> <div class="a"></div> .. <div class="sth1">< ...