Exploring the power of nested loops within an AJAX call in Angular

I have been attempting to iterate through a variable, search for IDs, and then make an ajax call to retrieve the detailed content of the different IDs. In the Success function, I am trying to loop through the received content and extract the emails.

While it is functioning correctly, I am encountering an issue where the first email is repeated twice in my $scope.subContactmail. I suspect there may be a problem with the loop structure, but I am unable to pinpoint the exact issue. I've spent the entire night trying to solve it without any luck. Ideally, the first loop should finish before moving on to the second loop. However, currently, the first loop continues into the second one.

Perhaps some experts out there could assist me in resolving this issue.

I eagerly await your assistance!

Here is a specific excerpt from my Angular app file:

//find all contract relations id's from customer
      $scope.contactrelation = function (input) {
      $http.post('http://localhost/mamiexpress/mamiAPI/includes/php/searchContactsRelation.php', input).
          success(function(data, status, headers, config) {
          $scope.subContactDetails =  [];
          $scope.subContactmail =  [];
          $scope.subContactId = data;
          console.log($scope.subContactId);

              //GET ALL the subcontact ID's from the selected item
                var i=0;
                var subContactIdlenght = $scope.subContactId.length;
                while  (i < subContactIdlenght) {
                console.log($scope.subContactId[i].contact_sub_id);
                var number = $scope.subContactId[i].contact_sub_id;
                i = i + 1;

              //Send the ID to the API and get the user Details
                $http.post('http://localhost/mamiexpress/mamiAPI/includes/php/searchContactswithID.php', number).
                    success(function(data, status, headers, config) {
                        $scope.subContactDetails.push(data); // store it in subContactDetails
                        console.log($scope.subContactDetails);


                       //HERE COULD BE THE PROBLEM!!
                       // I want this loop to start when the first loop is finished but i have to run this in this success function.
                       // At the moment i get the first email twice!

                       //Loop trough ContactDetails and get the emails.   
                       if (i == subContactIdlenght){ 
                           var subContactDetailslength = $scope.subContactDetails.length;
                              for(var p=0; p < subContactDetailslength; p++) {
                              console.log($scope.subContactDetails[p].mail);
                              var number = $scope.subContactDetails[p].mail;
                              $scope.subContactmail.push(number);
                              };   
                        };

                    }).
                    error(function(data, status, headers, config) {
                    $scope.errormessage = data;
                    console.log(data);
                    });

                 };//ENDWHILE


        console.log(data);
        }).
        error(function(data, status, headers, config) {
         $scope.errormessage = data;
          console.log(data);
        });

Answer №1

you've got 2 solutions

It's best to use the promise API:

something like this

var weatherPromise = $http.get(...);
var timePromise = $http.get(...);

var combinedPromise = $q.all({
    weather: weatherPromise,
    time: timePromise
})

combinedPromise.then(function(responses) {
    console.log('the weather is ', responses.weather.data);
    console.log('the time is ', responses.time.data);
});

OR

Alternatively, you can:

  • Create a separate function for your $http requests or consider using an AJS service.
  • Invoke that function within a for loop based on your list.
  • Inside the function, declare a scope variable with an empty array.
  • Push response objects into the array.

Avoid placing $http.get inside a for loop as it may lead to unexpected results.

Answer №2

It seems like the solution you're looking for involves utilizing the promises/deferred API.

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

Creating multiple objects using POST request with AJAX and Django Rest Framework

I am facing an issue while trying to allow a user to create a new list for a dashboard. The problem arises as follows: User creates the first list: The new list appears once User creates a second list: the second list appears twice User creates a third li ...

The JavaScript code is not running as expected!

i have this index.html file: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" ...

The proper translation of the HTML encoded string is not being rendered accurately within AngularJS

I am dealing with an HTML encoded string that looks like this: Sign up and get &lt;span class=&quot;strong&quot;&gt;Something for FREE!&lt;/span&gt; When I implement ngSanitize and ng-bind-html in my template as shown below: ...

What are some methods for postponing a SurveyMonkey survey prompt?

Seeking feedback on a new site launch in beta mode (full launch scheduled for March 28). We want to give users time to explore the site before showing a pop-up after 10 seconds. As I am new to coding JavaScript, any assistance would be greatly appreciated. ...

Condense a lineup of names into only two rows

I have a challenge where I need to showcase a list of names separated by commas, pulled from an array in my React component. The HTML output should appear as follows: <div> <span>Liza</span>, <span>Eric</span>, <span>Mic ...

When an item in the accordion is clicked, the modal's left side scroll bar automatically scrolls to the top. Is there a solution to prevent this behavior and

When I first load the page and click on the Sales accordion, then proceed to click on Total reported and forecasted sales, the scrollbar jumps back up to the top The marked ng-container is specifically for the UI of Total reported and forecasted sales He ...

execute a retrieval query on an html pop-up

I have recently created an HTML web resource that I am displaying when a ribbon button is clicked. Within this popup, there is a dropdown list that I intend to fill with records obtained through a fetchXml query. The issue I'm encountering is that de ...

Angular encountered an issue while attempting to access the property 'results' of an undefined value

I've got the code functioning perfectly, but for some reason I'm not getting any errors in the console log. It seems like I can't access results from an indefinite property. Any ideas on what could be causing this issue? I'm trying to m ...

I'm looking for guidance on effectively utilizing filter and map within the reducers directory to manipulate the workouts objects

I am encountering an issue while trying to send delete and update requests for the workout object. The error message indicates that the filter function is not compatible as it's being applied to an object instead of an array. Here is the snippet of co ...

The functionality of Javascript is being compromised when utilizing ng-repeat

Just recently diving into the world of AngularJs while developing a website. I've successfully retrieved data from Rest services on a page, and used ng-repeat to display it. The issue arises when I have a regular javascript element on the page that i ...

Issue encountered while subscribing to SalesForce topic using Node.js

Attempting to subscribe to a SalesForce topic through a Node.js server using the code provided in the JSForce documentation: conn.streaming.topic("InvoiceStatementUpdates").subscribe(function(message) { console.log('Event Type : ' + message.ev ...

Easily Update Your Div Content by Simply Clicking a Single Link/Button

I am in need of assistance here. My goal is to display dynamic content within a div. Below you will find the code I currently have: <script type="text/javascript"><!-- function AlterContentInContainer(id, content) { var container = documen ...

Expanding functions consist of numerous components

How can I modify this script to work on multiple elements? For example, if a user clicks on a specific link (see demo) labeled "I'd like to expand the article linked here", only that particular link should expand an element, not all like it currently ...

Parsing the CSV file contents according to the specified columns

Currently, I'm involved in a project using AngularJS where I need to extract data from a CSV file column by column using JavaScript. So far, I've successfully retrieved the CSV data and displayed it in the console. While I've managed to sepa ...

`res.render when all data queries are completed``

When I make an app.get request in my server.js file, I retrieve a dataset from MongoDB and then render my page while passing the data to it. Here is an example: //page load app.get('/', (req, res) => { //find all data in test table ...

What is the best way to merge different Vue JS instances (each linked to different html divs) into one cohesive unit using Vue

Essentially, I have a scenario where I've created two HTML divs named vueapp1 and vueapp2. Both of these divs serve the same purpose of displaying information and are linked to their individual Vue instances for extracting JSON data and presenting it. ...

Sending a JSonArray to a Spring controller can be achieved by making use of

How can I send a jsonArray using an Ajax call to the Spring controller? [{"REQUEST_ID":"BBBBBBB","MATCH_COUNT":"Accountant","CLIENT_ID":"Tokyo","MATCH_REASON":"63","NAME":"2011/07/25","FATHER_NAME":"$170,750"},{"REQUEST_ID":"CCCCCCC","MATCH_COUNT":"Junior ...

Is the Ajax component updating before the actionListener is activated?

My current setup involves using PrimeFaces <p:dialog> to open a popup HTML page and a <p:commandButton> to close it: When the Ok button is pressed, this is what happens: <p:commandButton id="submitButton" value="OK" actionList ...

effective ways to create a click outside functionality using ng-show and ng-hide

Can I create a solution that allows for click-away functionality using ng-show? Check out the plunker here: http://jsfiddle.net/o0dwsrqf/ I have a button that toggles the visibility of text. <button ng-click="test=!test">test</button> I&a ...

Error: Firebase has encountered a network AuthError, which could be due to a timeout, interrupted connection, or an unreachable host. Please try again later. (auth/network-request-failed

I have set up my Angular app to utilize Firebase's emulators by following the instructions provided in this helpful guide. In my app.module.ts, I made the necessary configurations as shown below: import { USE_EMULATOR as USE_AUTH_EMULATOR } from &apos ...