0

I want to rerun a PHP File which was loaded in a div in my HTML code. On my main page, I have a form and a table. The form adds rows to the MySQL table, and the table on the page outputs that MySQL table. I want the table on the HTML page to update when the new row is added via the form, without refreshing the page. I tried putting the load command in the success part of the ajax function for my form but that didn't work. I looked at many other answers and none worked for me.

This is my code

redeem.php

        <h1>Rewards</h1>
        <form id="add-reward-form" action="" method="POST">
                <label for="inputRewardDescription" class="form-label">Enter Reward Description</label>
                <input type="text" id=inputRewardDescription name="description" class="form-control" required>
                
                <label for="inputRewardCost" class="form-label">Enter Reward Cost</label>
                <input type="text" id=inputRewardCost name="points" class="form-control" required>
    
                <button type="submit" class="btn btn-success" id="submit-btn">Save</button>
        </form>  
        <p id="message"></p>
        <div id="sql-table">
            <?php include 'tables.php'; ?>
        </div>

tables.php

<?php
        $host    = "";
        $user    = "";
        $pass    = "";
        $db_name = "";

        //create connection
        $connection = mysqli_connect($host, $user, $pass, $db_name);

        //test if connection failed
        if(mysqli_connect_errno()){
            die("connection failed: "
                . mysqli_connect_error()
                . " (" . mysqli_connect_errno()
                . ")");
        }

        //get results from database
        $result = mysqli_query($connection,"SELECT RewardName, PointsRequired FROM rewards");
        $all_reward = array();  //declare an array for saving property
            while ($reward = mysqli_fetch_field($result)) {
                // echo '<th scope="col">' . $reward->name . '</th>';  //get field name for header
                array_push($all_reward, $reward->name);  //save those to array
            }
            // echo '      </tr>
            //         </thead>'; //end tr tag
            echo '<table class="table">
            <thead>
                <tr>
                <th scope="col">Reward</th>
                <th scope="col">Points Required</th>
                <th scope="col">Edit</th>
                <th scope="col">Delete</th>
                </tr>
            </thead>';
    
            //showing all data
            while ($row = mysqli_fetch_array($result)) {
                echo "<tbody>
                        <tr>";
                foreach ($all_reward as $item) {
                    echo '<td>' . $row[$item] . '</td>'; //get items using property value
                }
                echo '<td><i class="fas fa-edit"></i></td>';
                echo '<td><i class="fas fa-trash"></i></td>';
                echo '  </tr>
                    </tbody>';
            }
            echo "</table>";
    ?>

redeem-form.js

$(document).ready(function() {
    $("#add-reward-form").submit(function(e) {
        e.preventDefault();
        $.ajax( {
            url: "add_rewards.php", 
            method: "POST",
            data: $("form").serialize(),
            dataType: "text",
            success: function(strMessage) {
                $("#message").text(strMessage);
                $("#add-reward-form")[0].reset();
                $("#sql-table").load(" #sql-table > *");
            }
        });
        $("#sql-table").load(" #sql-table > *");
    });
    
});

The form works perfectly fine with ajax, and submits to the database without refreshing. But I would like to update the table on my page as well without reloading.

$("#sql-table").load(" #sql-table > *");

This is what I tried. I placed it inside the success function and the submit function but both did not work.

4
  • You have to make an ajax request to tables.php to refresh #sql-table. So it should be $("#sql-table").load("tables.php"); (.load() being a shorthand for ajax). Commented Jul 11, 2021 at 21:29
  • The PHP include only happens once, when the page is first fetched from the server, then that code goes away. You can't call it again from the browser. You'll have to either rebuild the table in JS, or generate it in PHP and call it with ajax.. Commented Jul 11, 2021 at 21:30
  • 1
    @LouysPatriceBessette thank you, that worked. Never knew the solution was that simple! Commented Jul 11, 2021 at 21:34
  • As-is, $("#sql-table").load(" #sql-table > *"); is attempting an ajax request to the url /%20#sql-table%20%3E%20* which obviously fails. Commented Jul 11, 2021 at 21:35

2 Answers 2

2

You are mis-using $.load(). It's a shorthand for $.ajax(). The first argument must be a URL. Optional arguments are data and options.

You are passing it a selector, so the request fails. As-is, $("#sql-table").load(" #sql-table > *"); is attempting an AJAX request to the URL /%20#sql-table%20%3E%20*. (!)

Simply change the selector for the PHP file you want to execute:

$("#sql-table").load("tables.php");
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the edit @kmoser, appreciated ;)
1

How about forcing redeem.php to re-evaluate the PHP div every time a change happens to the inputs?

        <h1>Rewards</h1>
        <script>
            function redrawSQLTable(){
                document.getElementById('sql-table').innerHTML = "<?php include 'tables.php'; ?>"
            }
        </script>
        <form id="add-reward-form" action="" method="POST">
                <label for="inputRewardDescription" class="form-label">Enter Reward Description</label>
                <input type="text" id=inputRewardDescription name="description" class="form-control" required onchange="redrawSQLTable()">
                
                <label for="inputRewardCost" class="form-label">Enter Reward Cost</label>
                <input type="text" id=inputRewardCost name="points" class="form-control" required onchange="redrawSQLTable()">
    
                <button type="submit" class="btn btn-success" id="submit-btn">Save</button>
        </form>  
        <p id="message"></p>
        <div id="sql-table">
            <?php include 'tables.php'; ?>
        </div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.