How can I ensure that a JavaScript function is called inside a foreach loop and waits for a response

Struggling with a puzzling issue here. There's a function called updateDate( id ) that updates a specific row in the database using an AJAX-call to a PHP-script. This process takes some time to complete.

Then there's another function named updateDates() which fetches all the IDs that need updating by making an AJAX-call to a different PHP-script. It then loops through these IDs and calls updateDate( id ) for each ID in the loop.

The problem arises when the loop doesn't wait for a response from updateDate( id ) before moving on to the next iteration. This results in multiple simultaneous AJAX-calls (2398572375 to be precise) causing glitches in the system.

Is there a way to make the loop pause until it receives a response from updateDate( id )?

The updateDate( id ) function returns true once the readyState of the AJAX-call is 4, indicating that the response is complete. I have tried adding this condition in the loop:

if( updateDate( id ) ) { Do something. }

But unfortunately, it didn't solve the problem. Any suggestions or insights on how to tackle this issue?

EDIT: Here are snippets of the code as requested.

updateDates():

function updateDates()
{

    ids = new XMLHttpRequest();

    ids.open( "GET", "<?php echo anchor("index.php/main/ajax/getIdsToUpdate"); ?>", true );
    ids.onreadystatechange = function() {

        if( ids.readyState == 4 )
        {

            var response = $.evalJSON( ids.responseText );
            if( response.type == 1 )
            {

                $.each( response.message, function( index, value ) {

                    if( value != '' )
                    {

                        if( updateDate( value ) )
                            alert('Checked: ' + value);

                    }

                });

            }

        }

    }

    ids.send(null);

}

updateDate( id ):

function updateDate( id )
{

    req = new XMLHttpRequest();
    req.open("GET", "<?php echo anchor("index.php/main/ajax/updateDate/"); ?>" + id, true);

    req.onreadystatechange = function() {

        if( req.readyState == 4 ) 
        {

            var value = $.evalJSON( req.responseText );

            // Updating a DIV on the site..

            return true;

        }

    }
    req.send(null);

}

Answer №1

Your provided code snippet lacks detail on how you're handling ajax calls and the structure of your code. However, one approach could involve initiating the next ajax call only after the successful completion of the previous one. Here is a pseudocode example:

var idArray = [];   // Assume this is an array containing IDs that require individual ajax updates.

function updateNextId(list, index) {
    if (index < (list.length -  1)) {
        ++index;
        var id = idArray[index]
        ajax(parmss, function() {
            // Handle success
            updateNextId(list, index);
        });
    }
}

An alternative solution could be to bundle all IDs into one ajax request and let the server manage multiple IDs efficiently.

Answer №2

Two effective methods exist to achieve this goal without sacrificing a synchronous (and locked) UI.

A. Implement a batch update PHP script

This approach is straightforward. Enhance your PHP script to accept a list of IDs and dates instead of processing them one by one. This is the most efficient and optimal solution.

B. Transition to a queue system

You can transform the updateDates() function into a dequeuing mechanism. Here's what this entails:

Whenever updateDates() is invoked, it removes the first element from the array of IDs that require updating, triggers the ajax function, and assigns updateDates as the callback for the Ajax request.

Pseudocode/rough outline:

function updateDates() {
    if(allDates.length == 0) return;

    var data = allDates.unshift();
    $.post('/save.php', { 'id': data.id, 'date': data.date }, updateDates);
}

Answer №3

One approach is to create a callback function that triggers once the AJAX operation finishes, then recursively invoke the updateDates function from there.

In a pseudo-code format:

function updateDates(items) {
    current_id = items[0];
    updateDate(current_id, oncomplete: function() {
        next_items = everything_but_current_item(items, current_id)
        updateDates(next_items)
    });
}

Although there is a risk of encountering a stack overflow due to excessive recursion, this method seems to be the most straightforward solution for implementation.

Answer №4

One approach you can take is to implement the jQuery looping method .each(), along with jQuery's $.ajax() function and incorporate a callback function:

$('your targeted element').each(function(){
  var currentElement=this;
  $.ajax(url,{
    success:function(responseData, status, xhr){
      //perform operation on 'currentElement' using 'responseData'
    } 
  });
});

The suggestion from earlier about utilizing a single AJAX request for multiple IDs is valid.

Answer №5

According to its acronym, AJAX refers to Asynchronous JavaScript and XML. This implies that it carries on without pausing for a response. To make it pause before proceeding, switch it to being synchronous instead.

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

Is there a way to switch the main image by clicking on different thumbnails in a sidebar using javascript/jQuery

Currently on my page, I have a large plot created with jqplot along with a sidebar containing several smaller plots. I am trying to find a way to dynamically change the large plot based on which of the smaller plots the user clicks on, without needing to ...

executing the following event in Node.js

Is it feasible to execute only a portion of the code on each iteration of the event loop in an application where requests can take a second or two? Consider the following scenario: function foo() { ...critical code... ...start processing the next ...

What is the best way to organize arrays with various combinations?

I am trying to rearrange the elements in 3 arrays: ["s","m"], ["Red","Black"], ["1", "2"]. My desired arrangement is as follows: ["s","Red","1"], ["s"," ...

Avoid Conversion of HTML Entities in Table Cells

<table> <tr> <td>&gt;</td> </tr> <tr> <td>&&#xfeff;GT</td> </tr> </table> In the code snippet above, I have table cells containing HTML entities. A re ...

What steps should I take to resolve the "You do not have authorization to access this directory or page" error in Azure App Services?

Currently, I am attempting to deploy my Next.js 13 application to AppServices using Github Actions. The compilation process on Github was successful, however, I am encountering an issue where my application does not seem to be deploying or starting up prop ...

While loop implementation for validating string inputs

I'm struggling with a simple code issue. The while conditions in my code are being ignored and the print statement is always executed. Can someone please assist me? package Checkpoints; import java.util.Scanner; public class Check05 { public st ...

Sending an excessive amount of requests can result in a failure, causing the entire website to become unresponsive

I'm currently developing a signup page that allows users to select a username that is not already in use in the database. To achieve this, I've implemented AJAX functionality. However, when multiple requests are made simultaneously, the system fa ...

Using Vue for Firestore pagination

Utilizing the bootstrap-vue pagination component: <b-pagination v-model="currentPage" :total-rows="rows" :per-page="perPage" ></b-pagination> Component.vue: export default class PaginatedLinks extends Vue { public currentPage: number ...

Guide to logging in using REST/API with a Next.js application

Issue: I am facing a challenge integrating with an existing repository that was created using Next.js. The task at hand is to enable users to sign in to the application through a specific endpoint or URL. To achieve this, I have been attempting to utilize ...

How can I pass the current value of an HTML.DropDownListFor to an ActionLink?

Is it feasible to transfer the current value of @Html.DropDownListFor to an action link? I am trying to send the template value to the Sample controller using the Create action. The code below is not functioning because @Model.SurveyTemplate does not retur ...

What can be used as an alternative to the onkeypress event for touch events?

For my text fields, I am currently utilizing the onkeypress event to validate numbers exclusively. However, this method is not effective for mobile devices (the page is designed to be responsive for both desktop and mobile use). Upon discovering that touc ...

Protractor's modal dialogue displays numerous outcomes when accessing ng-repeater elements

Trying to click on an element located within a repeater has presented some challenges. The issue arises from the fact that it is a modal dialog and returns multiple elements for the repeater. Each page in our application functions as a modal dialog, leadin ...

In React JS, you can't use the `map` function

I attempted to map out this response but encountered an error even after placing it in a usestate array. Please review my code to see if you can help me resolve the issue. function Comment() { const [comment_data, setcomment_data] = useState([]); u ...

Twice Asynchronous AJAX Action

Currently, I am working on a javascript script to dynamically load pages on my website without the need to refresh the entire page. The script involves fading out the content div, loading new content, switching the content, and then fading it back in. The ...

Order dates within an array by year in descending order, followed by arranging by month in ascending order, and then sorting

Upon receiving data from an AJAX to PHP call, I am presented with an array containing information about classes and the dates they were offered. Let's refer to this array as 'data': var data = [{ "course": "Mathematics", "courseDate": " ...

Scaling up the window size in Scalatest PlusPlay Selenium is causing resizing issues

After spending a good amount of time on this, I am struggling to figure out how to resize a window using scalatest plus. I have searched online and looked through the documentation at The method I found is executeScript("window.resizeTo(700, 700);") ...

Transitioning home screen (cursebird or foursquare)

Let me start by saying that I have a solid background in php/mysql, but I am new to learning jQuery and have only dabbled in ajax. I find it confusing when people use the terms ajax and jQuery interchangeably. My question relates to a website I am working ...

Display a div element within a JavaScript alert

I have implemented a jQuery script for my menu links on an index.php page. Specifically, when the user clicks on the 'Info' menu item, it loads sectionInfo.html into the index.php page. This section contains a short form that may trigger an alert ...

Content that is dynamically generated by a database

I have been working on creating a unique wall feature for my website, inspired by Facebook. My aim is to allow users to submit form data and have it validated before storing it in a database. Additionally, I want this stored data to be displayed in a desig ...

I would like to create a map showing the selected locations by checking them off using checkboxes

How can I draw a road map by selecting locations with checkboxes in form.php? After posting the selected locations to map.php file and assigning them to a $location array, how do I then assign these values to the waypoints array in the javascript calcRoute ...