简体   繁体   中英

Append Problem with JSON data to HTML Table

I have problem after showing json data to html table.

The problems;

  1. Every time i change the product_id, the table value always add new data.
  2. if the result is null, the tbody table still showing the current previous data.

Here's my code:

<table class="table" id="history_maintenance">
  <thead>
    <th>Date In</th>
    <th>SPK No</th>
    <th>Purchase No</th>
    <th>Maintenance Notes</th>
  </thead>
  <tbody></tbody>
</table>

<script>
$('#product_id').on('change', function() {

let customer_name = document.getElementById("customer_name").value;
let phone = document.getElementById("phone").value;
let car_plate_no = document.getElementById("car_plate_no").value;
let car_type = document.getElementById("car_type").value;
let product_id = document.getElementById("product_id").value;

$.ajax({
    type: "POST",
    url: "<?php echo base_url('spk/get_customer_transaction_history') ?>",
    dataType: "json",
    cache: false,
    data: {
        customer_name: customer_name,
        phone: phone,
        car_plate_no: car_plate_no,
        car_type: car_type,
        product_id: product_id,
    },

    success: function(dataHistory) {
      let transactionHistory = '';

      for (i = 0; i < dataHistory.length; i++) {
        transactionHistory += '<tr>';
        transactionHistory += '<td>' + dataHistory[i].date_in + '</td>';
        transactionHistory += '<td>' + dataHistory[i].spk_no + '</td>';
        transactionHistory += '<td>' + dataHistory[i].purchase_no + '</td>';
        transactionHistory += '<td>' + dataHistory[i].spk_maintenance_notes + '</td>';
        transactionHistory += '</tr>';
      }

      $('#history_maintenance tbody').append(transactionHistory);
    }
   });
   return false;
});
</script>

thanks @EL_vanja for the tips

i add this:

$('#history_maintenance tbody').html('');

before:

let transactionHistory = '';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM