Execute DataTables ajax.reload() Async before a function

Viewed 215

I am trying to source some data from the datatable I am working on. I have an edit button on every row and when is clicked it suppose to bring a form with the data that is already in the table for editing. I need to get real time data when the form is render however ajax.reload() doesn't load the table on time for the form be filled by the correct data and with code below only shows the form for the first employee:

    let editEmployeeId;

$(document).ajaxStop(function(){
$('#employeesTable tbody').on('click', '.btn.btn-warning.small-edit-button', function(){
  
  let thisRow = this;
  
  
  tableEmployees.ajax.reload(function(){
  
  //tableDepartments.draw();
  tableDepartments.columns().search("").draw();
  //tableEmployees.columns().search("").draw();
  getDropdown(1,'#departmentEditDropdown', 'Departments');
  var data = tableEmployees.row($(thisRow).parents('tr')).data() || tableEmployees.row($(thisRow).parents('li').attr('data-dt-row')).data();
  
  $('#editFirstName').val(data.firstName);
  $('#editLastName').val(data.lastName);
  $('#departmentEditDropdown>select').val(data.department);
  updateLocation('#locationEditDropdown','#departmentEditDropdown>select');
  $('#departmentEditDropdown>select').trigger('change');
  $('#locationEditDropdown>select').val(data.locationID);
  $('#editJobTitle').val(data.jobTitle);
  $('#editEmail').val(data.email);
  $('#editEmployeeModal').modal("show");
  
 });
});

I tried:

  • promise
  • settimeout
  • nested functions
  • async functions

I also try to change ajax call to set async: false and this way it works perfect but I don't think that is a good practice and I have other calls through the document and takes double of time to load the page first time.

1 Answers

I changed the way of calling the button with an extra class for the employees page and used the .click() method instead .on() because for some reason it was going in a loop with the last one. Now works and this is how it looks:

    let editEmployeeId;

$(document).ajaxStop(function(){
  
  $('.btn.btn-warning.small-edit-button.employees').click(function(e){
    e.preventDefault();
    let thisRow = tableEmployees.row($(this).parents('tr'));
  let thatRow = tableEmployees.row($(this).parents('li').attr('data-dt-row'));
  tableDepartments.columns().search("").draw();
  tableEmployees.columns().search("").draw();
  getDropdown(1,'#departmentEditDropdown', 'Departments');
    tableEmployees.ajax.reload(function(){
      var data = thisRow.data() || thatRow.data();
      editEmployeeId = data.id;
      $('#editFirstName').val(data.firstName);
      $('#editLastName').val(data.lastName);
      $('#departmentEditDropdown>select').val(data.department);
      $('#departmentEditDropdown>select').trigger('change');
      $('#editJobTitle').val(data.jobTitle);
      $('#editEmail').val(data.email);
      $('#editEmployeeModal').modal("show");
    })
  });
Related