Anson Aştepta
Anson Aştepta

Reputation: 1145

Ajax : Call multiple API with for loop

Since I need to call a brunch of data to make a chart, i need to call 10 or more different api so i created a function like this

function trend1() {
  return $.ajax({
    url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile0").html(), //getting the api
    type: 'get',
    success: function(data) {

    }
  });
}

function trend2() {
  return $.ajax({
    url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile1").html(), //getting the api
    type: 'get',
    success: function(data) {

    }
  });
}

function trend3() {
  return $.ajax({
    url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile2").html(), //getting the api
    type: 'get',
    success: function(data) {

    }
  });
}

function trend4() {
  return $.ajax({
    url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile3").html(), //getting the api
    type: 'get',
    success: function(data) {

    }
  });
}

function trend5() {
  return $.ajax({
    url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile4").html(), //getting the api
    type: 'get',
    success: function(data) {

    }
  });
}

function trend6() {
  return $.ajax({
    url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile5").html(), //getting the api
    type: 'get',
    success: function(data) {

    }
  });
}

function trend7() {
  return $.ajax({
    url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile6").html(), //getting the api
    type: 'get',
    success: function(data) {

    }
  });
}

function trend8() {
  return $.ajax({
    url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile7").html(), //getting the api
    type: 'get',
    success: function(data) {

    }
  });
}

function trend9() {
  return $.ajax({
    url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile8").html(), //getting the api
    type: 'get',
    success: function(data) {

    }
  });
}

function trend10() {
  return $.ajax({
    url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile9").html(), //getting the api
    type: 'get',
    success: function(data) {

    }
  });
}

$.when(trend1(), trend2(), trend3(), trend4(), trend5(), trend6(), trend7(), trend8(), trend9(), trend10()).done(function(trend1_data, trend2_data, trend3_data, trend4_data, trend5_data, trend6_data, trend7_data, trend8_data, trend9_data, trend10_data) {
  //do something                            
})

How may i put this massive code into a for loop? does ajax allow me to do this?

UPDATE 1:

function trend0()...
function trend1()...
function trend2()...
function trend3()...
....

$.when(trend1(), trend2()).done(function(trend1_data, trend2_data) {
for (var i = 0; i<N; i++) // with N your n* of cycles 
    eval("trend" + i + "()");
}

}

Am i doing something like below?

Solution :

                var i = "";
                for (var i=0; i<5; i++) {
                var trend = function(i) {
                    if ( $(".numberOfProfile"+i).length ) {
                        return $.ajax({
                            url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile"+ i).html(), //getting the api
                            type: 'get',
                            success: function(data) {

                            }
                        });
                    }
                    else
                    {
                      return false; 
                    }
                }
                    i++
                }

Upvotes: 0

Views: 1232

Answers (3)

arzhed
arzhed

Reputation: 438


Important : You should not write all the functions since they all seem alike ! It will be harder to maintain in the future

If you know the class number of profiles from an existing array, you should indeed loop over it. If it simply goes from 0 to 10 like above, you may go this way :

var responses = [];

for (var i=0; i<10; i++) {
responses[i] = $.ajax({
    url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile" + i).html(),
    type: 'get',
    success: function(data) {

    }
}

Note the actual response day will be found in responses[i]['response'], or more likely responses[i]['responseJSON']

EDIT: using $.when is a good idea, but you seem to have a quite long set of ajax calls to make so I cannot make the final decisions since I dont know the final application. From the examples above it would be like so :

var trend = function(profileNo) {
    return $.ajax({
    url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile" + profileNo).html(),
    type: 'get',
    success: function(data) {

    }
}

$.when(trend(0), trend(1), ..., trend(10)).done(function(t1, ..., t10) {
      //handle the results here
})

EDIT2 : I am actually surprised your new solution works. Have you tried it? In that spirit I would do it that way :

var trend = function(profileNo) {
        return $.ajax({
        url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile" + profileNo).html(),
        type: 'get',
        success: function(data) {
           //You could also use this callback to assign the retrieved to a "global" variable for instance 
        }
    });
}

var i=0;
var responses = [];

while($(".numberOfProfile"+i).length ) {
    responses[i] = trend(i);
    i++;
}

Upvotes: 1

Pawan Nogariya
Pawan Nogariya

Reputation: 8960

Your format seems fixed so you can do something like this.

function trend() {
    var trends = [];
    for(var i=0;i<10;i++)
    {
        var urlX = '/dashboard/getTrend' + '?period=30d' + "&profileId="+$(".numberOfProfile"+i).html(), //getting the api

         $.ajax({
             url: urlX
             type: 'get',
             success: function(data) {
                          trends.push(data);       
                       }
               });
      }
}

$.when(trend()).done(function(trendsData){
     // you have all the trends now
});

Upvotes: 0

Gumma Mocciaro
Gumma Mocciaro

Reputation: 1215

If the api call is the same all the time you can do a for loop

for (var i = 0; i<N; i++) // with N your n* of cycles 
    trend();
}

if they are different, you can do something (based on your code)

function trend0()...
function trend1()...
function trend2()...
function trend3()...
....

for (var i = 0; i<N; i++) // with N your n* of cycles 
    eval("trend" + i + "()");
}

eval will elaborate strings as javascript code https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval

Btw is not really performing to do something like that, i suggest you to find another way

If you want to call this functions on the page load you can do:

function trend0()...
function trend1()...
function trend2()...
function trend3()...
....

jQuery(document).ready(function(){
    for (var i = 0; i<N; i++) // with N your n* of cycles 
        eval("trend" + i + "()");
    }
});

or maybe on click action?

function trend0()...
function trend1()...
function trend2()...
function trend3()...
....

jQuery(document).ready(function(){
    jQuery('#myButtonId').click(function(e){
        e.preventDefault();
        for (var i = 0; i<N; i++) // with N your n* of cycles 
            eval("trend" + i + "()");
        }
    });
});

This is up to your app logic

Upvotes: 1

Related Questions