首页 > 解决方案 > How to refresh table data with Ajax

问题描述

How to refresh table data using Ajax, tried the below code , but it refresh the whole page rather than the particular section, the URL "/refresh" is a request to Slim(framework) which is turn call the PHP function "getData", the function "getData" is a Mysql query "select server_name from server_data", Results of changing the below line

$(".result").html(results); The whole page is refreshed $('#result').html(results); The data is not refreshed at all.

I need to just refresh the table data without refreshing the whole page when the refresh button is clicked.

<html>
    <script type="text/javascript">
        $(document).ready(function() {
        $('.refresh_data').click(function() {

            $.ajax({
                url: "/refresh",
                method: "GET",
                success: function(results) {
                        $('#result').html(results);
                }
            });
        });
    });
    </script>

    <body>
        <div align=right>
            <button type="button" class="bnt btn-info btn-dark btn-sm refresh_data">Refresh<i class="fa fa-refresh" aria-hidden="true"></i></button>
        </div>
    <div class="result"  align=center>
        <table id="hostTable" class="table table-striped table-bordered table-sm mb-0">
            <thead>
                <tr>
                    <th class="text-center h6 th-sm font-weight-bold">Server Name</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>name</td>
                </tr>
            </tbody>
        </table>
    </body>
</html>

From, Akash.V

标签: ajaxrefreshusing

解决方案


First of all the content is not refreshed when $('#result').html(results); because #result does not exist, the only result in the html is a class so .result.

So in order for this to work the code has to be: $('.result').html(results); .

Second problem, are you sure that the response is HTML?

And to finish, check for load function. .load(), maybe it will suite your needs better.

.load( url [, data ] [, complete ] )

Description: Load data from the server and place the returned HTML into the matched elements.


推荐阅读