Search code examples
jqueryajaxdatabasedatatable

How to call Ajax on condition


I have a varible voyagekey. When I click on a row in the table, there will be a voyagekey of that ship. enter image description here

Based on the value of that voyage key, how can the ajax call display only the data lines that contain the voyage key variable? My Ajax call code currently only loads the datatable.

The variable to save when I need to find a suitable ship is voyagekey, and the field in the datatable I want to upload is VoyageKey.


$('#Form1, #Form2, #Form3').find('tbody').on('click', 'tr', function () {
  var vesselName = $(this).find('td:eq(0)').text();
  var groupvoyage = $(this).find('td:eq(2)').text();

  console.log('vesselName:', vesselName);
  console.log('voyagekey:', voyagekey);
  // Gán giá trị cho trường input
  $('#chooseVessel').val(vesselName);
  $('#chooseVoyage').val(groupvoyage);

  

  let me = $(this);
  // select me
  me.toggleClass('selected');
if (me.hasClass('selected')) {
  me.css('background-color', '#4987a2');
} else {
  me.css('background-color', '');
}

me.parent().find('.selected').not(me).removeClass('selected').css('background-color', '');

  // if three rows are selected, then do something
  // (there can only be one row in each table that is selected)
  if ($('.selected').length === 3) {

// Gọi ajax để load dữ liệu dựa trên voyagekey
$.ajax({
  type: "POST",
  url: '/Tally/Tally/get',
  data: { voyagekey: voyagekey },
success: function(result) {
 // Xử lý dữ liệu nhận được và hiển thị lên bảng ContentTable
 var data = result.data;
  if (data.length === 1) {
    data[0].STT = 1;
  } else {
    // Duyệt qua từng hàng và cập nhật STT
    $.each(data, function(index, row) {
      row.STT = index + 1;
    });
  }
      table.clear().draw();
      table.clear().rows.add(result.data).draw();
//      table.show();
         
},
error: function(xhr, status, error) {
console.log(xhr.responseText);
}
});
        }
      });

The form table and datatable both have a voyagekey field, each ship name will have its own voyagekey field containing that ship's name. I want when I click on a ship's name, I only call ajax to the data table of the fields that have the same voyagekey. The first image shown is the voyagekey of the formtable. I saved to variable to compare with voyagekey in database. These are voyagekeys saved to the variable. enter image description here Here is the list of ships to filter enter image description here


Solution

  • I had to add WHERE : VoyageKey to the query on the Modal file. This helped me to filter the VoyageKey field data to match the voyagekey array in my View file.