What is the best way to execute a series of AJAX functions one after the other in JavaScript?

Currently, I am working on a project that involves editing multiple elements within a window simultaneously using AJAX. My goal is to have all "open for editing" elements saved when the user clicks the save button for the entire window.

However, I encountered an issue where an anchor tag was used around images instead of onclick functions, forcing me to use the eval function to call the necessary actions.

Here is the code snippet I am using for the window-wide save button:

var as = document.getElementsByClassName('link_salvare');
alert(as.length);
for(var i = 0; i < as.length; i++) {
    alert(i);
    eval(as[i].href);
}
alert('finished');

After testing, I discovered that the 'for' loop stops after the first iteration (i=0) even though there are two editing elements present. Whether using asynchronous or synchronous AJAX calls, I still cannot get all elements saved.

While I could potentially resolve this by allowing only one element to be edited at a time, I need approval to make changes to individual save functions post-weekend.

For now, I managed to work around this issue by:

a) Converting from

<a href="javascript:function"><img>
to <img onclick="function"> to avoid using eval;

b) Adjusting the window layout so that only one element can be edited at any given moment.

Although the core problem remains unresolved, these workarounds ensure smooth functionality until further investigation can be done.

Answer №1

Discussing the use of the eval() function.... However, it seems like there are no other issues present in your code. You touch on ajax (XmlHttpRequest) but there are no errors or related code provided.

Markup

<a href="javascript:foo()" class="foobar">yoyo</a>
<a href="javascript:bar()" class="foobar">yoyo</a>​

JavaScript

var elements = document.getElementsByClassName('foobar');

function foo() {
    alert('foo');
}

function bar() {
    alert('bar');
}

[].forEach.call(elements, function(element) {
    var func = element.href.split(':')[1],
        func_name = func.substring(0, func.lastIndexOf('('));
    window[func_name].call();
});​

I strongly advise against using a workaround like this and recommend modifying the HTML source instead. Here is a possible solution: http://jsfiddle.net/rlemon/4vgPn/2/

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

A guide on scheduling automatic data insertion in mongoose.js

I'm working on a website with Node.js and Mongoose, and I could use some guidance on how to automatically insert data into Mongoose with Node.js at specific times. For example, at the end of each month, I want my current data to be stored in the Mongo ...

Cannot update VUEjs array following the splice operation

My array is only updating in the console and not in the DOM. I've already tried using :key but it's still not working. Here is my code: <div style="margin-top: 5px;" v-for="(file, index) in editedItem.file_name" ...

What steps can be taken to add a radio button group to a form in order to choose between the smoking and non-smoking sections of a restaurant?

I'm trying to replicate the functionality of radio buttons within a bootstrap form-group, where a line in a form contains multiple buttons ("btn btn-success" for example) that can be selected, but only one at a time. I am aiming for an output like thi ...

Attempting to showcase a list of 4 concatenated items in a dropdown menu sourced from the database

I am attempting to concatenate and display 4 items in a dropdown list using AJAX. For example, the value in the dropdown list should appear as (127, CoilWt, 1, KGS) from the database. In the database, I am selecting select CODE_VALUE, CODE_DESC, CODE_SUB ...

What is the best way to efficiently query a substantial dataset using Node.js in an asynchronous fashion?

I need to extract data from a mysql database by fetching 10 rows at a time until I reach 400k rows. To achieve this asynchronously, I am using recursion as shown in the code below: var migrate = function(offset, size) { Mysql.query(query, [offset, size] ...

Preventing Ajax from Running Multiple Times

I am currently working with CakePHP framework 2.0 and I am facing an issue where my AJAX function is running multiple times. I have created dynamic elements which is why I am using the click function below: $(document).on('click','.save&apo ...

Convert the JSON data received from a jQuery AJAX call into a visually appealing HTML table

Utilizing AJAX as the action, I have created a search form. In the success of the AJAX request, I am seeking a way to update a specific div without refreshing the entire page. Below is my form: <?php $properties = array('id' => &ap ...

Implementing a Radial Cursor with a Custom Background Image in JavaScript

I am attempting to implement a radial cursor on a website that features a background image. Currently, I am facing two main issues: The radial cursor works in Chrome but not in Firefox. When using Firefox, I encounter a parsing error related to the "bac ...

Passing a function into the compile method in AngularJS: A comprehensive guide

I have created a directive called pagedownAdmin with some functionality to enhance the page editor: app.directive('pagedownAdmin', ['$compile', '$timeout', function ($compile, $timeout) { // Directive logic here... }]); ...

Having trouble with my Express.js logout route not redirecting, how can I troubleshoot and resolve it?

The issue with the logout route not working persists even when attempting to use another route, as it fails to render or redirect to that specific route. However, the console.log("am clicked"); function works perfectly fine. const express = require('e ...

To close modal A in ReactJS using React-Bootstrap after opening modal B from modal A, follow these steps:

When the registration button is clicked, a signup modal appears. Is there a way to then open a login modal from within the signup modal, ensuring that the signup modal closes once the login modal pops up? show={this.props.signupModalOn} onHide={this.props. ...

Where can I locate a specific child element in this scenario?

Currently, I am exploring the possibilities of integrating AngularJS into my application and have encountered a question regarding the click event implementation. Within my HTML code: <div ng-click='clickMe()' ng-controller='testCtrl&ap ...

Ways to share code across AngularJS frontend and Node.js backend

How can code be effectively shared between an AngularJS client and a Node.js server? After creating an AngularJS application, I now need to develop a RESTful server to provide data to the client. Some Angular services used on the client-side could also be ...

Caution: React is unable to identify the `PaperComponent` prop on a DOM element

Trying to create a draggable modal using Material UI's 'Modal' component. I want users to be able to move the modal around by dragging it, so I decided to use 'Draggable' from react-draggable library. However, I encountered this er ...

Navigating with AngularJS through link redirection using anchor tags

How can I achieve smooth scrolling to a specific section using angularJS when clicking on a link? When clicking on a link like this: The page instantly redirects to the specified footer section. I want to implement an angular controller to handle this fun ...

The readyState is stubbornly refusing to reach 4

I have been working on developing a dynamic AJAX search bar that interacts with my database. Below is the code I have been using. function getXmlHttpRequestObject(){ if(window.XMLHttpRequest){ return new XMLHttpRequest(); } else if (window.ActiveXObj ...

Perform Action Only When Clicking "X" Button on JQuery Dialog

I have a dialog box with two buttons, "Yes" and "No", which trigger different functions when clicked. $('#divDialog').dialog({ modal:true, width:450, resizable: false, buttons: [{ text: 'Yes', ...

Button-controlled automated presentation

I have devised a method to create an automatic slideshow using JavaScript. However, I am looking to incorporate manual control buttons as well. After adding manual control code, the slideshow seems to be malfunctioning. The provided code below is used for ...

Allowing Cross-Origin Resource Sharing in WKWebView for IOS9

When trying to load a local HTML file on IOS using WKWebview with loadFileURL and allowingReadAccessToURL, I encounter an issue when sending ajax requests. An error message is displayed: "Origin null is not allowed by Access-Control-Allow-Origin." I a ...

Utilizing AngularJS to implement a Currency Filter on the output of a personalized filter

I'm currently working on a custom filter that transforms zero values into ' - ' for display purposes. The goal is to display currency formatting for non-zero values. However, I encountered an unexpected token error while trying to implement ...