user3652549
user3652549

Reputation: 69

How to refresh table with jquery ajax?

I have the below table. With ajax call I am updating the content of the table. It is reflected in the database, but how can I refresh the table without reloading the entire page. Please someone guide me.

My table structure:

<table class="table table-hover" id="cust-table">
    <thead>
        <tr>
            <th>LastName</th>
            <th>FirstName</th>
        </tr>
    </thead>
    <tbody>
        <?php
            for($i=0; $i<$numrows; ++$i) {
                 $contacts = mysqli_fetch_assoc($result);
            ?>
        <tr>
            <td><?php echo $contacts['LastName']; ?></td>
            <td><?php echo $contacts['FirstName']; ?></td>
        </tr>
        <?php
        } ?>
    </tbody>
</table>

Jquery code:

$.ajax({   
       type: 'POST',   
       url: 'update.php',   
       data: {LastName:last_name, FirstName:first_name}
     });

the update.php is updating the database but I need to refresh the table without refreshing the entire page. Can someone please help me on this?

Upvotes: 5

Views: 20376

Answers (2)

vineet
vineet

Reputation: 14236

For your scenario, write code for html table and ajax in other pages. For example:-

In update.php

//do stuff for update
//html table code
------------------------

In ajax page(test.php)

<div id='load'>

</div>

<script>
$(function(){
loadData();

// call by click event
$('#selector-name').click(function(){
     loadData();
});


function loadData(){
    $.ajax({   
     type: 'POST',   
     url: 'update.php',   
     data: {LastName:last_name, FirstName:first_name},
    success: function(msg) {
            $("#load").html(msg);
        },
    });
  }
});
</script>

Upvotes: 2

Dirk
Dirk

Reputation: 41

This should be easy.

    //delete all rows in table
    $('#cust-table').empty();

    //add rows
    $('#cust-table > tbody:last').append('<tr> ... </tr>'); //do the magic

Upvotes: 2

Related Questions