Retrieving the output of a function is essential

I am a beginner with AngularJS and JavaScript. I have a question regarding my code where, after calling the function, I am getting d as a result. Could you please review the code below and let me know what I am doing wrong? Thank you. Here is the code snippet:

     function volunteerNumbr (ProspectID){
        var value1;

        console.log("volunteerNumbr[i].ProspectID",ProspectID)

        $http.get(baseURL + 'participant/prospectid/'+ProspectID).success(function(participantData, status, headers, config){

            var participantData=JSON.stringify(participantData);

            if(JSON.parse(participantData) == null){
                value1 =  -1;
                //console.log ("$rootScope.value1",$rootScope.value);
            }
            else{
               value1 = JSON.parse(participantData).length;
                console.log ("$rootScope.value2",$rootScope.value);
            }

        }).error(function(data, status, header, config) {
                console.log("failed to fetch data")
            });

         console.log ("$rootScope.value3",value1);
         return value1;
    }

    $http.get(baseURL + 'prospect/all/').success(function(data, status, headers, config) {

        $scope.prospects = data;    // display data in list

        var prospect=JSON.stringify($scope.prospects);
        var prospect=JSON.parse(prospect);

        var prospectLength = prospect.length;

        for(var i = 0; i < prospectLength; i++){
            prospect[i].num = volunteerNumbr(prospect[i].ProspectID);
        }

        console.log("all prospects",prospect);

    }).error(function(data, status, header, config) {});

Answer №1

$http.get() doesn't return the data directly, but instead gives you a promise object.

If you want to assign the value prospect[i].num within the success block as shown below: Create a function by wrapping the $http.get inside an IIFE (Immediately Invoked Function Expression) and pass the current index value from the loop to ensure that the index value is retained for that particular ajax call.

JS Code:

$http.get(baseURL + 'prospect/all/').success(function(data, status, headers, config) {
$scope.prospec = data;    //display data on list

var prospect=JSON.stringify($scope.prospec);
var prospect=JSON.parse(prospect);

var prospectLength = prospect.length;

for(var i = 0; i < prospectLength; i++){

      //Creating an IIFE and enclosing $http.get inside it
      (function (index) {
      $http.get(baseURL + 'participant/prospectid/'+prospect[i].ProspectID).success(function(participantData, status, headers, config){

        var participantData=JSON.stringify(participantData);
        if(JSON.parse(participantData) == null){
            prospect[index].num =-1;
             }
        else{
            prospect[i].num =JSON.parse(participantData).length;
                                }
    }).error(function(data, status, header, config) {
            console.log("error")
        });
     }(i));

     console.log("num",prospect[i].num);
      }
console.log("all prospect",prospect);
$scope.prospects= prospect;
console.log("all $scope.prospects",$scope.prospects);

}).error(function(data, status, header, config) {});

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

Troubleshooting jQuery.ajax - Why won't it function properly?

I've been struggling to get the ajax service functioning properly. I tried a simple $.get("http://google.com"), but it didn't work. Additionally, this code snippet failed as well: <html> <head> <script src="https://aja ...

Using GeoJson in Leaflet for map display

As I develop an Angular application with Leaflet, my goal is to showcase numerous municipalities within my country: https://i.sstatic.net/9cuSW.png In order to enhance navigation efficiency, I decided to divide my JSON file into multiple files and store ...

Utilizing JavaScript regex for patterns such as [x|y|z|xy|yz]

Looking for a regex solution: \[[^\[\]]*\]\s*[<>|<=|>=|=|>|<]\s*'?"?\w*'?"? This regex is designed to parse equations like: [household_roster_relationships_topersona_nameadditionalpersono] = ...

When using jQuery and AJAX together, it seems that the POST method is returning

Currently experimenting with Cloud9. The current project involves creating an image gallery. On the initial page: There are a few pictures representing various "categories". Clicking on one of these will take you to the next page showcasing albums fro ...

Choosing a class using Jquery through a For loop in Javascript

I have a group of images with a class applied to them. I am attempting to create a for loop that will iterate through the elements of this class. In Python, you can use "for element in thing" and I was curious if there is something similar in JavaScript. A ...

Javascript continues to execute even after the designated element has been eliminated or substituted

I'm currently working on a WordPress auction site using WooCommerce that needs a countdown timer to display when a specific product auction is ending. Below is the JavaScript code for the countdown timer: const getElem = elem => document.q ...

What is the best way to access an element's sibling using JQuery within a function?

How can I use JQuery to set an element to match the value of its sibling? In a table with multiple fields, when clicking an Edit button, I want to copy the label value to its adjacent input field: <table style="width:90%"> <tr> <td&g ...

Navigate through set of Mongoose information

I have a challenge where I need to retrieve an array of data from Mongoose, iterate through the array, and add an object to my Three.js scene for each item in the array. However, when I try to render the scene in the browser, I encounter an error that say ...

Using webpack to access a bundled React class in an HTML file

Is there a way to access pre-built components directly within the HTML file that links to the build? I've been attempting the following - Inside bundle.js var React = require('react'); var ReactDOM = require('react-dom'); ...

Styling hyperlinks upon exporting an HTML table to Excel

I am trying to export an HTML table to Excel using JavaScript by following the instructions provided in Export HTML table to Excel its downloading table contents to the Excel. However, I have encountered an issue where one of the columns in my table conta ...

Locating a specific element within an array using AngularJS / Conditional statement within ng-class

I am working on a feature where I need to identify the current user in a list of all users. Below is an example of what my code currently looks like. <div class='user' ng-repeat='user in users'> <span class='name'& ...

construct a table utilizing JSON information

If I have data returned from an ajax call that needs to be processed, a table like the following needs to be created: ID NAME Object Type ============================================== 1 SWT-F1-S32-RTR-1 Network Switch 2 ...

The error message "Access-Control-Allow-Origin" header is not present when making an Ajax call to ReactJS localhost

While following the ReactJS tutorial, I set up a local server using the following commands: >npm install -g http-server >http-server -c-1 After successfully starting the local server at http://localhost:8080, I encountered an issue when trying to ...

Tips on how to update the styling of an active link

http://jsfiddle.net/G8djC/2/ Looking to create a tabbed area where content changes based on the tab clicked. The Javascript function switches the link class to active upon clicking. However, struggling to change the color of the active tab beyond the firs ...

Alter the input background color steadily through javascript transformation

Is there a way to gradually fade in a new background color using JavaScript only? I am currently changing the background color with the following code: // html <input onfocus="onFocus(this)" onblur="onFocus(this)" type="text"> // JS function onFoc ...

Organize intricate JavaScript Arrays

Similar Question: How to sort an array of javascript objects? I'm in the process of transitioning some of my older ActionScript 2.0 code to JavaScript. While most things are running smoothly, I've hit a roadblock when trying to numerically s ...

Exploring arrays to find the maximum sum of elements

Struggling to develop a Javascript function that identifies which element in an array of numbers (specifically phone numbers) has the highest sum? Despite feeling frustrated and defeated, I believe I am on the right track. Could someone provide some guidan ...

Working with PHP to transfer toggle switch information to JSON

I'm currently experimenting with a combination of HTML, JavaScript, and PHP on a single page. My goal is to update a JSON file with either 0 or 1 based on the toggle switch state change. I seem to be close to achieving this functionality, but upon rel ...

Importing a TypeScript library that depends on another library

Currently, I am in the process of creating a TypeScript library. As part of this project, I have incorporated the https://github.com/Simonwep/pickr library. My goal is to make the library easily accessible for users, but I am uncertain about whether I sh ...

Using iTextSharp in .Net to convert the action result into a downloadable pdf file via ajax

I have been successfully using iTextSharp to convert a razor view into a downloadable PDF via a C# controller. While the current implementation is functioning perfectly, I am seeking a way to transmit a model from a view to the PDF controller and enable th ...