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

Utilizing Server-Sent Events to display a interactive navigation button

Currently, I am managing a web-based point of sale system where some buttons are hidden for specific functions. To streamline the process, I would like to allow managers to simply click on an "Enable" button in the admin panel and have it immediately refle ...

Remove an image using Ajax in Laravel without the need to reload the page

I need help with deleting an Image using Ajax without having to reload the entire page. Currently, when I try to delete the Image, it doesn't get removed immediately. However, upon refreshing the page, the deletion takes effect. app.js: $('.del ...

Is it possible to create a dynamic template in Angular using external sources?

My goal is to dynamically load HTML content using AJAX and then compile it, as it contains Angular directives. I have a specific class that includes methods for utilizing Angular outside the scope of an angular controller or directive: var AngularHelper ...

JQuery fails to retrieve accurate width measurements

Utilizing this code snippet, I have been able to obtain the width of an element and then set it as its height: $(document).ready(function(){ $(".equal-height").each(function(){ var itemSize = $(this).outerWidth(); cons ...

Vue is struggling to load the component files

Lately, I've been encountering an error during webpack build that is causing some issues. ERROR There were 3 errors encountered while compiling The following relative modules could not be found: * ./components/component1.vue in ./resources/assets/ ...

Upload files via Ajax request is required

I am in the process of trying to upload a binary file to a server while avoiding a full page refresh when the server responds. I must admit, I am not well-versed in this area and I understand if my approach needs some adjustments. This is how I have appro ...

Tips for altering objects within an array

I am dealing with an array of objects that looks like this: const items = [ {name: 'Sam', amount: '455gbjsdbf394545', role: 'admin'}, {name: 'Jane', amount: 'iwhru84252nkjnsf', role: 'user'}, ...

Guideline on extracting private keys from Windows Certificate Manager

I am currently working in a Windows environment setting. Within my organization, we act as our own certificate authority for internally-used https applications. I have obtained a certificate from our system for a private web server I created. While using ...

Unable to reset the input value to an empty string

I have created a table with a search bar feature that filters the data when the search button is clicked and resets the filter to show unfiltered data when the clear button is clicked. However, the current input value is not clearing from the display even ...

How to dynamically alter a PHP variable using a JavaScript button click on the existing webpage

I've spent the last hour scouring stackoverflow for answers to my problem, but trying out solutions has only resulted in errors - perhaps because I'm attempting to implement it on the same page. I've experimented with saving the value to a ...

The chai property "matchSnapshot" is not valid

https://i.sstatic.net/4wgqq.png After following the instructions provided at this link, I am now in the process of writing basic Jest tests for my React application that uses the Create-React-App starter kit. I came across a recommendation mentioned here ...

Retrieve the Date information and transfer it to another page using a combination of jQuery, JavaScript, and PHP

I feel defeated trying to solve this problem. Can anyone offer assistance in figuring this out? I've spent an entire day debugging with no success. I have two PHP files, index.php and home.php. In the index.php file, I include the Date range picker, ...

Which HTTP headers pertain to the loading of iframes? nuxt-helmet

Can anyone explain which security headers are associated with iframe loading issues and may prevent the iframe from being loaded? I implemented nuxt-helmet to configure security headers in my nuxt project. However, after uploading my site to a server loca ...

What is causing the error message "Error: Cannot update active font: 'Fira Sans' is not included in the font list" in react-font-picker?

For my project, I have implemented a font picker component in the following manner: <FontPicker apiKey={process.env.REACT_APP_GOOGLE_API_KEY} activeFontFamily={activeFontFamilyMobile} ...

The interaction issue in Ionic 4 with Vue js arises when the ion-content within the ion-menu does not respond to clicks

My Vue app has been set up with Ionic 4 using @ionic/vue. Below is the code snippet from the main.js file: import Vue from 'vue' import App from './App.vue' import router from './router' import store from './store&apos ...

I have been seeking the perfect solution to seamlessly incorporate ckeditor5 with comments in my AngularJS applications. Despite extensive research, I have not come across any angularjs-specific plugins for this purpose. It

import Comments from '@ckeditor/ckeditor5-comments/src/comments'; ClassicEditor.builtinPlugins = [ Essentials, Paragraph, Bold, Italic, Image, Comments ]; I am trying to figure out how to incorporate comments into the CKEditor5 in an AngularJS ...

Unable to align text within a DIV using CSS

Recently, I started learning jQuery and building my own website. You can find my project on JSFIDDLE. The issue I'm facing is that when hovering over a new div, the text extends beyond the borders of that div instead of staying within it. I've sp ...

Transferring a header across a series of interconnected services

I have a script that calls two services, combines their results, and displays them to the user. The services are: Service 1 (hello) and Service 2 (world), resulting in "Hello world". I want to include an ID in the headers to track the route of the calls. ...

Facing an issue with webpack-dev-server where it displays a blank screen

Hello! I am currently in the process of creating my first MERN stack application, using Webpack as the build tool. The main objective is to have Express serving the APIs for the app and webpack-dev-server handling the static content (from my static directo ...

Scrolling through a list while the user types in the search bar

I am currently working on a table that populates based on an array of country objects, and I have added a search bar to enable live filtering through the countries array. However, as a newcomer to Vue, I am struggling to implement this feature effectively. ...