0

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);
      }
    }]
  });
});

1 Answer 1

1

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/

Sign up to request clarification or add additional context in comments.

3 Comments

Hey! Thanks for your answer, the only thing i'm not understanding is: where should i put this code, i mean on which part of my own code?
The data goes in the html, in the table, and you read the data from html into javascript where you do var statusVal = $(this).data("status"); and add one more parameter this way?
Thank you! Could you just make a fiddle so that i can get it better?

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.