skip to Main Content

I need to do thousands of AJAX GET Request – they need to be nested due to their dependency (which means: the next AJAX request uses variables from the response of the previous one).

I managed to request as many times as I could with the example below, but this is a case where I need to do it thousands of time, so impossible to write them like this.

I tried to write loops in many ways, but they all resulted in a non-expected behavior.

$.ajax({
        url: 'urllink.com',
        beforeSend: function(xhr) {
             xhr.setRequestHeader("Accept", "application/json")
        }, success: function(responseJSON){

            var jsonResponse = Object.values(responseJSON).pop()
            alert(jsonResponse);


$.ajax({
        url: 'urllink.com'+jsonResponse,
        beforeSend: function(xhr) {
             xhr.setRequestHeader("Accept", "application/json")
        }, success: function(responseJSON){

            var jsonResponse = Object.values(responseJSON).pop()
            alert(jsonResponse);

           

        }


})
        }


}) 

4

Answers


  1. You could make a function to make ajax calls and another function to call first function in a loop and then you pass the result parameter in each iteration

     function calls(val){
      var   res=$.ajax({
        url: 'urllink.com'+val,
        beforeSend: function(xhr) {
             xhr.setRequestHeader("Accept", "application/json")
        }, success: function(responseJSON){
      
            return Object.values(responseJSON).pop()
        }
     }).responseText
     return res
    }
    var val="intialvalue"
    async function makecalls(){
      for (let i=0;i<1000;i++){
        var param= await calls(val)
               val=param
      }
    }
    
    Login or Signup to reply.
  2. let count = 0;
    function req(url, amount) {
        let recall = this.req;
        $.ajax({
            url: `${url}`,
            beforeSend: function (xhr) {
                xhr.setRequestHeader("Accept", "application/json")
            },
            success: function (responseJSON) {
                var jsonResponse = Object.values(responseJSON).pop()
                alert(JSON.stringify(jsonResponse));
                count++
                if (amount > count) {
                    recall(url, amount);
                }
            }
        });
    };
    
    req('urllink.com', 2);
    

    What I did was making a recall variable that runs itself with the same parameters, and then just check for the count to execute itself.

    Login or Signup to reply.
  3. Consider a scaffold like the following. Each asynchronous request will run concurrently and spawn it’s own replacement when done. Details are left as an exercise.

    let i = 1000;
    
    function doRequest() {
        // some state advancement and termination condition
        // this can include the “target url” which can be supplied
        // as a parameter (eg. function doRequest(url)): adjust accordingly.
        if (i <= 0)
            return;
        i = i - 1;
        let x = i;
        console.log(x + “ starting”);
    
        $.ajax({
            ...,
            success: function () {
                 // don’t use alert here! >_<
                 console.log(x + “ done”);
                 // function has access to it’s own name
                 // (this is a form of “stack less” recursion)
                 // start the next asynchronous call!
                 // tip: pass some “next url” result data for this problem
                 doRequest();
            }
            // also handle failure case
        );
    }
    

    The concurrent self-replacing requests can be started N parallel times for independent subproblems. Browsers have a limit of a few parallel requests at a time (eg. 2..8 are common, well short of hundreds). The remote server may have even lower parallel capabilities.

    // example only, call once with “start url” for this task
    // as the specific problem establishes a data dependency
    // and the requests cannot be run in parallel
    // unless there is a method to divide the problem
    for (let n = 0; n < 8; n++) {
        doRequest();
    }
    

    Free typos, iPhone makes this hard 🙁

    Login or Signup to reply.
  4. Assuming that all requests are in order that they all provide a next property in response object until the very last one not having that property (or it’s value returns falsy) you should be able to use the following recursive promise chain.

    End result will be an array of all the next values returned

    const  getData = (path, results=[]) => {
       let url = 'urllink.com' + (path || '');
       // return an ajax promise 
       return $.getJSON(url).then(({next}) => {
           if(next){
             // store current value in results array
             results.push(next);
             // return another request promise
             return getData(next, results); 
           } else {
             // when run out of nexts return the array of data to the final then()
             return results;
           }
       });
    }
    

    Usage:

    getData().then(data => console.log(data))// array of all the `next` values received
             .catch(err => console.log('Ooops, one of the requests failed'));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search