如何在不使用JavaScript重新加载页面的情况下在数据库中执行操作?

如何在不使用JavaScript重新加载页面的情况下在数据库中执行操作?

问题描述:

I've wrote a code which retrieve some data in table and each row has a two button which is responsible for updating database with a fixed value for that row and deleting the row. I want to do these actions without reloading page. here is my table code:

<table id="example1" class="table table-bordered table-striped">
    <thead>
    <tr>
        <th>نام کاربر</th>
        <th>ایمیل</th>
        <th>تایید</th>

    </tr>
    </thead>
    <tbody>
    <?php
    while ($users = mysqli_fetch_assoc($result_user)) {
        ?>
        <tr>
            <td><?php echo $users['name']?></td>
            <td><?php echo $users['email']?></td>
            <td>
                <div class="btn-group">
                    <button name="btn_confirm" type="button" class="btn btn-success btn-flat">تایید</button>
                    <button type="button" class="btn btn-success btn-flat dropdown-toggle" data-toggle="dropdown">
                        <span class="caret"></span>
                        <span class="sr-only">Toggle Dropdown</span>
                    </button>
                    <ul class="dropdown-menu" role="menu">
                        <li><a name="btn_delete" href="#">حذف</a></li>
                    </ul>
                </div>
            </td>
        </tr>
    <?php }?>
    </tbody>
</table>

You need to use AJAX as @Sagar Sainkar said.

You can find a good explanation on this post:

jQuery Ajax POST example with PHP

So I will not rewrite the whole mechanism again. It explains very well how you can plat with ajax, js and php (which I noticed you use).

Another TIP: avoid mixing up back-end and front-end code. Don't integrate php scripts in HTML files. Try writing separate JS files (containing the requests), import them into your HTML code and use them there (and if they do not load graphical content that the user needs to see when the page loads, then defer it, or put the import of the JS at the bottom of html). There may be better options but one easy to delete or update rows using AJAX is to pass a parameter to the server like "command: delete_entry" or something similar and then switch between options on the back end. But there are smarter options out there if you research well, you can use this tip plus the tutorial passed to start playing with AJAX requests until you master get a good grip upon them.

In order to update DOM elements without refreshing the page you will need to be able to send data or action request to a server (API) and then wait for their response to update your page accordingly.

You can refer to https://github.com/axios/axios which is one of the more popular library to learn how to call a POST or GET request.