Jack022
Jack022

Reputation: 1257

Submitting table's data with Javascript with HTML Datatables

I have a simple datatable that shows some JSON data received from an API. I edited my table so that, for each row, there is a button that, when hit, will send an Ajax request to a URL containing the value for that specific row.

Below is the function that will send the request, and the function that will render the table. There are three columns on my table, when the X button is hit, the value of the column id for that row will be sent as an Ajax request to an external URL.

This code works, but the only problem is that, along with the value of id, i would like to edit the table so that, when the button is hit, the value of the column item will be sent together with id, so that my ajax request can send item and id, not only id. Can someone give me some advice on how to do that? Thanks in advance!

$(document).ready(function() {
  $(document).on('click', '.btnClick', function() {
    var statusVal = $(this).data("status");
    console.log(statusVal)

    callAJAX("/request_handler", {
      "X-CSRFToken": getCookie("csrftoken")
    }, parameters = {
      'orderid': statusVal
    }, 'post', function(data) {
      console.log(data)
    }, null, null);

    return false;
  });

  let orderstable = $('#mytalbe').DataTable({
    "ajax": "/myview",
    "dataType": 'json',
    "dataSrc": '',
    "columns": [{
      "data": "item"
    }, {
      "data": "price"
    }, {
      "data": "id"
    },],
    "columnDefs": [{
      "targets": [2],
      "searchable": false,
      "orderable": false,
      "render": function(data, type, full) {
        return '<button type="button" class="btnClick sellbtn" data-status="replace">X</button>'.replace("replace", data);
      }
    }]
  });
});

Upvotes: 0

Views: 52

Answers (1)

Victor Pudeyev
Victor Pudeyev

Reputation: 4539

Use html data attributes, then get them from the row that's being clicked/worked on, and send that along.

<col data-item="$thisItem" id="a1" ><button class='a1' /></col>
$.click((e) => {
  let class = "a1"; // use the relevant references or use jQuery's parent(), etc
  let colId = $("col#"+class);
  let data = colId.data['data-item']; // this way you have your item info in the scope, and you can send it.

from: https://api.jquery.com/data/

Upvotes: 1

Related Questions