[Answered ]-Django update template div with success data from Ajax

1๐Ÿ‘

โœ…

As your data return is json you can use $.each loop to iterate through your json array then use value.keyname to get value from json and append these values inside tds and finally add this html generated inside your table tbody.

Demo Code :

//suppose this is return from ajax
var books = {
  "books": [{
      "id": 1,
      "code": "LKG001",
      "type": "BOOK",
      "name": "LKG BOOK 1",
      "open_qty": "0",
      "recived_qty": "328",
      "return_qty": "0",
      "issue_qty": "111",
      "adj_qty": "4",
      "bal_qty": "213",
      "avgcost": "100.55",
      "price": "100.00"
    },
    {
      "id": 2,
      "code": "UKG001",
      "type": "BOOK",
      "name": "UKG BOOK 1",
      "open_qty": "0",
      "recived_qty": "17",
      "return_qty": "0",
      "issue_qty": "9",
      "adj_qty": "0",
      "bal_qty": "8",
      "avgcost": "200.00",
      "price": "200.00"
    },
    {
      "id": 3,
      "code": "UKG002",
      "type": "BOOK",
      "name": "UKG002 BOOKS",
      "open_qty": "0",
      "recived_qty": "0",
      "return_qty": "0",
      "issue_qty": "0",
      "adj_qty": "1",
      "bal_qty": "-1",
      "avgcost": "0.00",
      "price": "200.00"
    },
    {
      "id": 4,
      "code": "001",
      "type": "BOOK",
      "name": "001 TEST",
      "open_qty": "0",
      "recived_qty": "0",
      "return_qty": "0",
      "issue_qty": "0",
      "adj_qty": "0",
      "bal_qty": "0",
      "avgcost": "0.00",
      "price": "0.00"
    }
  ]
}


/*$(document).on('change', '#book_type', function(){
   var that = $(this)
 $.ajax(
    {
        type: "GET",
        url: "/get_stock_list",
        dataType: "json",
        data: {
            'book_type': $(this).val(),
            'csrfmiddlewaretoken': '{{csrf_token}}'
        },
        success: function (books) {
            console.log(books);*/
var html = "";
//loop through json array return
$.each(books.books, function(key, value) {
  //append tr
  html += `<tr> <td> <a href="{% url 'select_stock_report' ${value.id} %}">${ value.code }</a></td><td>${value.name}</td><td>${value.open_qty}</td><td>${value.recived_qty}</td><td>${value.return_qty}</td><td>${value.issue_qty}</td><td>${value.adj_qty}</td><td>${value.bal_qty}</td></tr>`
})

$('#stock_list tbody').html(html); //add datas inside tbody
/* }
    })})*/
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="card-body" id="stock_list">
  <table id="customers">
    <thead>
      <tr>
        <th>Item Code</th>
        <th>Item Description</th>
        <th>Open Qty</th>
        <th>Received qty</th>
        <th>Return Qty</th>
        <th>Issue Qty</th>
        <th>Adj Qty</th>
        <th>Balance Qty</th>
      </tr>
    </thead>
    <tbody>
      <!--data will come here -->

    </tbody>
  </table>
</div>
๐Ÿ‘คSwati

Leave a comment