Acquire information asynchronously in JavaScript while inside a for loop

Recently, I've been exploring this particular function snippet:

function add_cnh(arr_clelem){

  var id=arr_clelem.getElementsByClassName("present")[0].id;
  var date=arr_clelem.getElementsByClassName("present")[0].getAttribute('date');
  var tt_entry= arr_clelem.getElementsByClassName("present")[0].getAttribute('tt_entry'); 


//new Ajax.Updater('register', '/some_url', { method: 'get' });

new Ajax.Request('/attendances/new',
{
    parameters:'id='+id+'&date='+date+'&timetable_entry='+tt_entry+'&subject_id='+subject_id,
    asynchronous:true,
    evalScripts:true,
    method:'get'
 /*onSuccess: function(transport) {
var response = transport.responseText || "no response text";
alert("Success! \n\n" + response);
}*/

}
)
var ret=modal_data;
  // $$('.MB_close').invoke('observe', 'click', _deinit);
return ret;

}

This unique function works by taking html-elements-object as an argument and ultimately rendering a modal-box. The modal box contains form elements that need to be stored inside an array. Interestingly, the variable modal_data holds the necessary elements and is defined globally in another file.

An issue I'm encountering pertains to the outdated nature of the project. The various JavaScript frameworks and libraries utilized date back to 2006, with even the library responsible for opening the modal box being deprecated as evidenced here.

To address this challenge without delving into server-side solutions, I've resorted to employing a for loop strategy:

for(var i=0; i<arr_of_elements.length, i++)
{
   my_arrvar[i]=add_cnh(arr_of_elements[i]);
}

Throughout each iteration, my goal is to close the modal box and store the data within 'my_arrvar'. However, the asynchronous nature of the call has posed obstacles despite attempts using closures and callbacks. Avoiding timer usage, the process revolves around calling the function, retrieving data for each call, and removing the modal box by ID.

Additionally, I am curious if leveraging this technique could offer a solution, and if so, how?

Answer №1

To ensure synchronous processing in an ajax request, set asynchronous:false instead of true. This is the only way to achieve it.

Alternatively with jQuery

A convenient method is to utilize the .ajaxStop() event handler:

$(document).ajaxStop(function() { // Add code here to run when all ajax calls are complete });

For more information, visit jQuery Event handler

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

Recalling the layout following the user's computer restart

I am creating a simple online editing tool (similar to Microsoft Outline) for coursework and I would like the outline details to be saved even if the user restarts the system. How can I achieve this? <html> <head> <title>Editor</ ...

troubleshooting problems with jquery ajax and setInterval

$(document).ready(function() { function refreshBids() { var element = $("#biddingDiv"); element.load("bids.php?id=<?=$userId;?>&init=1&auctionid=<?=$auctionId;?>"+(new Date()).getTime()); } refreshBids(); setI ...

Switching from Localstorage to AsyncStorage in React Native

I am working on storing a JSON object in both local storage and async storage. The following code snippet is for local storage and it works correctly in a web environment: useEffect(() => { const value = localStorage.getItem(`myData${id}`); cons ...

Node.js JSDOM unable to locate the 'parsingMode' property in the code

Is there a way to interact with the DOM of a JavaScript file using Node.js? var fs = require('fs'); var jsdom = require('jsdom'); var doc = jsdom.jsdom(fs.readFileSync("a.html"), null, { features: { FetchExt ...

Looking for a node.js asset manager for converting coffeescript, jade, and stylus files to JS and CSS?

I specialize in using coffeescript, jade, and stylus for my projects. My task involves creating two separate "one page apps" where I need to include all assets within the initial payload. My goal is to consolidate, compile, and merge all coffeescript fil ...

Guide to refreshing extensive dataset using MySQL migration scripts

We are in the process of developing a Nodejs application for a client who has requested that we use migration scripts to streamline updating the production database. As someone new to MySQL, I am struggling with how to update table contents using only MySQ ...

Using @PathVariable in Spring MVC can cause issues with Ajax functionality

I am facing an issue where I need to incorporate an ajax function on a specific page, but it seems to be not working with @PathVariable in spring mvc. page1.jsp <li><a href="page2/sss">WatchEvent</a></li> 1) It is working pr ...

I'm attempting to retrieve information from my vuex store, however, encountering an error in the process

I've encountered an issue with vuex getters while working on my project. I have a route that showcases all users, and upon visiting this route, the AllUsers.vue component is displayed. Within this component, I'm utilizing the UsersList.vue compo ...

The size of the Webpack bundle grows with each subsequent build

For my project, I am utilizing webpack to package it as a library. The project consists of a components library, and for each component residing in its own directory under src/ui, I am creating small bundles. Here is an example component structure: src/ ...

VueJS not refreshing DOM after AJAX data modification

Utilizing Vue.js to make changes to my DOM, I have implemented the fetch_data() method. This method attempts to update data.messages to display 'Love the Vue.JS' once the AJAX call is successfully completed. The AJAX call executes successfully a ...

How can I arrange individual events in agendaWeek view on FullCalendar.io and then merge them all into one line?

I am using Fullcalendar.io version 2 When I switch to the agendaWeek mode, all my events are displayed on one line in each day square. As a result, the more events I have, the thinner the event blocks become. Is there a way for me to display only one eve ...

The variable 'firebase' is nowhere to be found

I am encountering an issue with the error message 'Can't find variable: firebase' and I am struggling to identify the cause of this error. I have installed firebase using 'yarn add firebase' and double-checked that it is properly i ...

Guide to integrating a deterministic game loop with tick-based mechanics

My current project involves creating a "simple" 3D game using Three.js and incorporating a network framework for multiplayer functionality in the future. After some research, I found that many "action" games utilize a "tick" based game loop to sync clients ...

Using jQuery UI datepicker - how to set a parameter based on a specific condition

New to the world of JavaScript, I am trying my hand at implementing the jQuery UI datepicker widget. My goal is to add an additional line to the widget parameters if the variable selectedDate has a value. However, my current approach seems to be ineffecti ...

Learn the process of dynamically updating the source of an HTML5 video

Currently, I am working on a project that involves dynamically loading multiple videos onto a webpage. The structure of my HTML is quite straightforward - it consists of a single video tag. <video controls preload width="520" height="350" id="video"> ...

What is the significance of a listener signaling an asynchronous response with a return of true, only to have the communication channel close before the response could be received?

Currently, I am developing a React application that involves the use of various npm modules. One of these modules is a self-built NPM package called modale-react-rm (available at this link). This package serves as a simple modal component that utilizes the ...

Optimizing workflow with express.js, backbone.js, and connect-assets for maximum efficiency

As a newcomer to node.js, I'm embarking on the challenge of setting up an application that utilizes Backbone.js on the client-side while being supported by express.js and node.js for server-side extensibility. The lack of online examples showcasing a ...

How can I create a script for a sliding/toggling menu?

Not sure if it's appropriate to ask, but I'm currently in search of a slide/toggle menu. Despite my efforts on Google, I haven't been able to find exactly what I need. As someone who is more skilled in HTML/CSS than jQuery or other scripting ...

NodeJS produces identical outcomes for distinct requests

RESOLVED THANKS TO @Patrick Evans I am currently working on a personal web project and could use some assistance. In my website, users are prompted to upload a photo of their face. When the user clicks the "upload" button, the photo is sent with a request ...

Refreshing div content based on dropdown selection without reloading the page

I am currently working on implementing a dynamic dropdown feature that will update text content on a webpage without needing to refresh the entire page. The updated text will be fetched from a PHP function which receives input from the dropdown selection. ...