Perform an asynchronous reload of DataTables using ajax.reload() before calling a function

I need help extracting real-time data from a datatable and populating a form for editing when an edit button is clicked on each row. Despite my efforts, the ajax.reload() function doesn't load the table in time to fill the form with correct data. The code snippet provided only displays 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");
  
 });
});

In attempting to solve this issue, I have tried using promises, setTimeout, nested functions, and async functions. I also experimented with changing the ajax call to set async: false, which resolved the problem but slowed down page loading significantly. This solution doesn't seem to be a good practice, especially considering other calls within the document.

Answer №1

I made a change in how I called the button by adding an extra class for the employees page and using the .click() method instead of .on() because it was causing a loop issue with the last one. It is now functioning properly and this is the updated code snippet:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The JavaScript code is not being executed, as the address bar displays the function name instead

In my project, I have created numerous "js-classes" with various functions spread across different files. Unfortunately, the codebase is too large to share entirely. However, towards the end of the project, I encountered a bug where a specific function wa ...

Error in NodeJS when trying to run ESM: "ReferenceError: exports is not defined

Having a tough time with this task. I'm attempting to execute ESM scripts on Node 14 (AWS Lambda) I am working on running this piece of code to convert 3D objects to THREE JSON. This involves using the command node -r esm fbx2three.js model.fbx. I ...

React Native - Invariant Violation: Objects cannot be used as a React Child (Utilizing Node.js for the backend)

Trying to calculate the total sum of orders and their quantity using Node JS on the backend. However, encountering issues with the fetch functions not working properly or missing something unknown. The API works as expected when tested in Postman, but err ...

Unable to deploy the Firebase function to Firebase functions platform

I've been watching Doug's video on YouTube for guidance on changing a message with functions in JavaScript. To resolve the error message 'types can only be applied to ts files,' I installed the Flow language script. Thankfully, that err ...

Guide to displaying PHP output in a format suitable for plotting

I'm currently working on plotting PHP output from a MySQL database using . The desired format for the output should look like this - var data = [ { x: ['giraffes', 'orangutans', 'monkeys'], y: [20, 14, 23], ...

Having trouble with the JQuery class selector?

Having a bit of trouble trying to select an element based on its class using $(".class"), and I can't seem to figure out why it's not working. So, the deal is - I have this image element that should appear when a function gets triggered: $("#co ...

Instruct Smarty to display the block exactly as it is

Struggling to inline some JavaScript code into the Smarty template files due to the {ldelim} {rdelim} markers. Is there a way to instruct Smarty to disregard the markup and just output it as is? Any similar approach like CDATA blocks in XML? Just demonstr ...

Is there a way to retrieve a single value using AJAX instead of returning the entire HTML page?

(edited after initial version) I'm facing an issue where my AJAX call is returning the header.php page instead of just the $result value which should be 0 or 1. The AJAX function calls generateTicket.php, where I want to generate tickets only if no o ...

Issue with accessing container client in Azure Storage JavaScript library

When working on my Angular project, I incorporated the @azure/storage-blob library. I successfully got the BlobServiceClient and proceeded to call the getContainerClient method, only to encounter this error: "Uncaught (in promise): TypeError: Failed ...

Remove all Visual Composer Shortcodes while preserving the content

I'm in the process of transferring 200 posts from a previous WordPress website, which contain numerous visual composer shortcodes within the content. Is there a method to remove all the shortcodes and retain the content? ...

Issues with the drop-down menu in the <s:select> element arise when attempting to set the

While utilizing a Map to populate the Struts2 tag <s:select >, I have noticed that when the form is submitted multiple times, a blank line is added at the end of the list. For example, if the Map contains 2 key-value pairs, it displays 3 records and ...

The combination of Nest, Fastify, Fastify-next, and TypeOrm is unable to locate the next() function

In my attempt to set up Nest with Fastify and Next using the fastify-next plugin, everything went smoothly until I added TypeOrm for MongoDB integration. Upon loading the AppModule, Nest throws an error indicating that the .next() function cannot be found ...

A guide on dynamically altering text upon hovering over an element using Vue.js

On my website, I have the following HTML code: <div class="greetings"> <img @mouseover="hover='A'" @mouseleave="hover=''" src="a.png" alt="A" /> <img @mouseover="hover='B'" @mouseleave="hover=''" ...

The image being displayed is significantly wider than the corresponding HTML element

I'm attempting to display this webpage in PNG format using npm's wkhtmltox: <!doctype html> <html> <head> <meta charset="utf-8"> <style> html, body { padding: 0; width: 340px; } ...

Issue with Passport Google Oauth login redirection to successful route

I am currently following a tutorial on setting up Google Oauth in my Express app using Passport.js. The tutorial can be found here. Below are the routes defined in my server.js file: // Code snippet here The server.js file also imports configurations fro ...

Using jQuery AJAX to send a URL as a string parameter

Currently, I have an ajax function that sends a string of variables to my script. However, there is one variable that needs to hold a complete URL along with parameters. In the current setup, var1 and var2 are received as $_POST variables. But I specifica ...

What is the best way to implement a dropdown in MUI and React that displays functional components as items?

Here is a list of dummy components: const OwnerList = () => { return ( <Box sx={{ display: 'flex', }} className="owner-container" > <Avatar src='https://hips.hearstapps.com/hmg- ...

Fetch data using Ajax without the need for a hash signal

My current goal is to load content through Ajax on a website. Let's say our main page is example.com/blankpage (I've eliminated the .html extension using htaccess). At the moment, I have it set up so that when a link on the page directs to mysite ...

Steps for removing the label associated with an input field in an HTML form

I attempted to use JQuery and JavaScript in order to modify the CSS of a label to make it greyed out, but unfortunately I have not been able to achieve this. The label is positioned next to a checkbox, and although I am able to disable the checkbox, I hav ...

Is there a way to track and monitor the ngRoute requests that are being made?

I am in the process of transferring a fairly large Angular 1.6 application from an old build system to Yarn/Webpack. Our routing is based on ngRoute with a complex promise chain. While sorting out the imports and dependencies, I keep encountering this err ...