Issue arises when a specific number of ajax calls are made consecutively in a loop

My current project involves the importing of an excel file in xlsx format. The file is converted into an array of objects, with each object representing a row from the excel sheet. I then utilize a forEach loop to iterate over the array and create a data object based on each excel row. Here is an example:

resultArray.forEach((arr) => {
        let data = {
          action: 'addPestChem',
          crop: arr['Crop'] ? arr['Crop'] : null,
          company_name: arr['Company Name'] ? arr['Company Name'] : null,
          product: arr['Product Name'] ? arr['Product Name'] : null,
          substance: arr['Substance'] ? arr['Substance'] : null,
          function: arr['Function'] ? arr['Function'] : null,
          pcs_no: arr['PCS No'] ? arr['PCS No'] : null,
          phi: arr['PHI'] ? arr['PHI'] : null,
          use_by_date: arr['UseByDate'] ? arr['UseByDate'] : null,
          date_of_reg_review: arr['DateofRegReview'] ? arr['DateofRegReview'] : null,
          off_label_approval: arr['OffLabelApproval'] ? arr['OffLabelApproval'] : null,
          latest_time_of_application: arr['LatestTimeOfApplication'] ? arr['LatestTimeOfApplication'] : null,
          max_individual_dose: arr['MaxIndividualDose'] ? arr['MaxIndividualDose'] : null,
          max_total_dose: arr['MaxTotalDose'] ? arr['MaxTotalDose'] : null,
          max_no_applications: arr['MaxNoApplications'] ? arr['MaxNoApplications'] : null,
          method_of_application: arr['Methodof Applic'] ? arr['Methodof Applic'] : null,
          content: arr['Content'] ? arr['Content'] : null,
          comment: arr['Comments'] ? ['Comments'] : null
        };

        console.log(data);

        $.ajax({
            url: "/assets/ajax/excel_ajax_handler.php",
            type: "POST",
            data
        })
        .done((res) => {
            console.log(res);
        })
        .fail(function($xhr) {
            var data = $xhr.responseJSON;
            alert('An Error occured: ');
            console.log(data.message);
        });

      });

After creating the data object, an ajax call is made to a handler. Currently, for testing purposes, the handler echoes back '1'. However, upon running the code, '1' is logged around 118 times before the .fail() function starts triggering. Any insights on why this behavior occurs?

Answer №1

Avoid using ajax in a loop.

Here's an alternative approach

document.getElementById('uploadAll').addEventListener('click',post)
let count = 0
const post = () => {
  if (count >= resultArray.length) return;
  const array = resultArray[count]
  const data = {
    action: 'addPestChem',
    crop:                       array['Crop']                    || null,
    company_name:               array['Company Name']            || null,
    product:                    array['Product Name']            || null,
    substance:                  array['Substance']               || null,
    function:                   array['Function']                || null,
    pcs_no:                     array['PCS No']                  || null,
    phi:                        array['PHI']                     || null,
    use_by_date:                array['UseByDate']               || null,
    date_of_reg_review:         array['DateofRegReview']         || null,
    off_label_approval:         array['OffLabelApproval']        || null,
    latest_time_of_application: array['LatestTimeOfApplication'] || null,
    max_individual_dose:        array['MaxIndividualDose']       || null,
    max_total_dose:             array['MaxTotalDose']            || null,
    max_no_applications:        array['MaxNoApplications']       || null,
    method_of_application:      array['Methodof Applic']         || null,
    content:                    array['Content']                 || null,
    comment:                    array['Comments']                || null
  };

  console.log(data);

  $.ajax({
      url: "/assets/ajax/excel_ajax_handler.php",
      type: "POST",
      data
    })
    .done((response) => {
      process(response); // create a function to handle the response
      count++
      setTimeout(post,1000);
    })
    .fail(function($xhr) {
      var errorData = $xhr.responseJSON;
      alert('An Error occurred: ');
      console.log(errorData.message);
    });

};

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

What causes Angular to redirect to the route but display the incorrect view?

There is a fundamental issue I have encountered while working with routes: I have multiple routes defined If the user is not authenticated, they are redirected to the login page The problem lies in the fact that, on the initial display of the web app, t ...

jQuery - Reveal one div while concealing another

I've been working on a script to toggle between two divs onClick - opening one while closing the other if it's already open. I'm fairly new to jQuery and Javascript, having mainly worked with HTML/CSS. Script I found: http://jsfiddle.net/J ...

AngularJS display of SQL Server PIVOT table results

I am facing a challenge in returning data from the SQL server to the view. My question is about how to dynamically return column titles from the database to a table in an Angular app view. As new entries are added to the person table in the database, new c ...

Clicking on AngularJS ng-click to navigate to a different page within an Ionic framework application

My goal is to navigate to another page when clicking on a button in the Ionic navbar at the top. However, I am encountering an issue where upon clicking, all nav bar buttons disappear. Interestingly, using dummy codes triggers an alert successfully. But w ...

The variable "require" has not been declared in npm.js file at line

Apologies if this is a simple issue, but I have not been able to find a solution in my research. I am using the latest release of Bootstrap and have noticed a new file called npm.js compared to previous versions. All Bootstrap files are hosted locally on m ...

Show the textbox automatically when the checkbox is selected, otherwise keep the textbox hidden

Is it possible to display a textbox in javascript when a checkbox is already checked onLoad? And then hide the textbox if the checkbox is not checked onLoad? ...

Four images are loaded sequentially in a single scroll in the sequencer

I am facing an issue with this plugin's jQuery code. Currently, the code allows only one image to move in one scroll. However, I need to make four images move one by one in a single scroll sequence. Additionally, I would like to set a specific time in ...

What scenarios call for utilizing "dangerouslySetInnerHTML" in my React code?

I am struggling to grasp the concept of when and why to use the term "dangerous," especially since many programmers incorporate it into their codes. I require clarification on the appropriate usage and still have difficulty understanding, as my exposure ha ...

Identifying when a fetch operation has completed in vue.js can be accomplished by utilizing promises

Currently, I am facing a dilemma in my Vue.js application. I am making an API call within the created() hook, but there are certain tasks that I need to trigger only after the API call has been completed. The issue is that this API call usually takes aroun ...

Send binary information using Prototype Ajax request

Currently, I am utilizing Prototype to send a POST request, and within the postdata are numerous fields. One of these fields contains binary data from a file, such as an Excel spreadsheet chosen by the user for upload. To retrieve the contents of the file ...

What triggers the invocation of the onerror handler in XMLHttpRequest?

I am facing a bit of confusion when trying to understand the functionality of XMLHttpRequest's handlers. After reading the specification regarding the onerror handler, it mentions: error [Dispatched ... ] When the request has failed. load [Dispa ...

Obtain attributes from an array of objects organized by the individual objects

Hello there! I am currently working with an array called artists[] which consists of Proxy objects. Each Proxy object is also an array of objects, with each inner object containing a property called "artistName". Interestingly, the third Proxy ha ...

When attempting to parse a single string stored in a cookie with JSON.parse, it results in a "SyntaxError: Unexpected Number" error being thrown

I am facing an issue with parsing a string stored in a cookie. "d967fac49ef2466239168bbbde0a8d755a27ba81$[[\"__json_message\"\05425\054\"This is a message.\"]]" Also known as "\"d967fac49ef2466239168bbbde0a8d755a27ba81 ...

The function given to requestAnimationFrame is not being triggered as expected

I have successfully implemented an infinite loop animation using setInterval. However, I want to enhance the performance by switching to requestAnimationFrame(). Unfortunately, the function supplied to requestAnimationFrame() is not being called for some r ...

What is the best way to navigate between different areas of an image using html and javascript?

I am currently in the process of learning how to develop mobile applications, and I am still in the early stages. Although this question is not directly related to mobile development, it pertains more to html/css/js. My goal is to create a simple game wh ...

Updating an HTML input field property with JavaScript is not reflecting the changes

I am currently working on a form with two fields: stationery type and stationery request quantity. The stationery request quantity field only accepts numerical input. The minimum quantity that can be entered in this field depends on the value selected in t ...

Tips for Rearranging Columns in an Array of Objects

I have an array of objects that I need to rearrange the columns and add a static value to each one: var homes = [ { "h_id": "3", "city": "Dallas", "state": "TX", "zip": "75201", "price": ...

An altered picture is sketched

https://i.sstatic.net/0yQS3.png https://i.sstatic.net/4tltn.png https://i.sstatic.net/2hwGH.png https://i.sstatic.net/3iaDf.png https://i.sstatic.net/aphGY.png Html <!doctype html> <html lang="en"> <head> <meta charset=&q ...

Have I got it all wrong with the way Controllers communicate with Services and how I conduct unit testing?

Currently, I am in the process of developing an AngularJS application and I want to ensure it follows best practices. When making external API calls using either $resource or $http, I always do this within a separate Service or Factory. However, I am unsur ...

Does the organization of files and directories (such as modular programming) impact the speed at which AngularJS loads?

Can breaking code into smaller modules help decrease loading time? Exploring ways to modularize AngularJS applications can lead to a well-structured approach for developing large apps. This approach aims to streamline the development process by organizing ...