0

My problem is when i click the button to show the data from database to html table it shows up but when i try to click the button again it duplicates the content of the table and it continues to duplicate as long as i click the button.

script:

$('#showData').click(function() {

    $.ajax({
        url: 'Oppa/view/file.php',
        type: 'post',
        data: {tag: 'getData', code: $('#emailCodeResult').val()},
        dataType: 'json',
        success: function(data) {
            if (data.success) {
                $.each(data, function(index, record) {
                    if ($.isNumeric(index)) {
                        var row = $("<tr />");
                        row.appendTo("#myTable2 tbody");
                    }
                })
            }
            $('#myTable2').dataTable({
                "bjQueryUI": true,
                "bFilter": false,
                "bRetrieve": true,
                "sPaginationType": "full_numbers",
                "bAutoWidth": true,
                "bPaginate": false,
                "bInfo": false,
                "bLengthChange": false
            });
        }
    });
});
3
  • What would you like it to do, refresh the data? Commented Jul 31, 2014 at 13:48
  • Remove the rows at each update, otherwise you keep appending Commented Jul 31, 2014 at 13:48
  • you should check this stackoverflow.com/questions/13670579/… Commented Jul 31, 2014 at 13:51

2 Answers 2

3

Use $("#myTable2 tbody").empty() to remove the rows before appending:

success: function(data){
        if(data.success){
            $("#myTable2 tbody").empty(); //<------------------------------------
            $.each(data, function(index, record){
Sign up to request clarification or add additional context in comments.

Comments

0

Try $('#myTable2 tbody').empty(); before fetching your JSON Array. This will remove existing rows of your Table before adding new ones. The Table Header will remain though.

EDIT:

Changed from .remove() to .empty() based on comment below

2 Comments

$('#myTable2 tbody').empty();
Only difference is that $('#myTable2 tbody').remove(); removes the tbody tag as well :)

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.