skip to Main Content

I want to call ajax in a loop, while my URL is also changed in each iteration.
problem: I get the same last respond, from both 2 iterations.

I tried to use closure, as suggested in Javascript loop with ajax call
but the responds are still the same.

maybe the problem comes because I use request.responseText instead of jsonData

so –

  • How can I use jsonData ?

    or

  • How can I get different request.responseText in each iteration ?

sample code:

  function getLimitedSysInfo() {
      var $myObjects = $('.some-class');
      $myObjects.each(function() { 
          var objId = $(this).attr('id');
          var eId = objId.substring("my_obj".length);    
          
          (function(eId) { // use closure: https://stackoverflow.com/questions/43191608/javascript-loop-with-ajax-call

              var strURLGet = "http://www.test.com/my_test/get_info.php?p1=p1val&e=" + eId;
              console.log(eId + " -> " + strURLGet); // => prints out as expected
                
              request = $.ajax({
                  type: "get",
                  url: strURLGet,
                
                  cache: false,
                  complete: function(jsonData) { 
                      console.log("fSys() complete");  // => prints out as expected         
                  },
                  success: function(jsonData) { 

                      console.log("fSys() success");   // => prints out as expected
                
                      console.log("fSys() success " + eId + " -> ***" + request.responseText + "***" );  // => Here is the problem:
                          // => eId prints out as expected  
                          // => but request.responseText is the same for both calls


                      var myJSON = JSON.parse(request.responseText); // => so I always get the same JSON    
                      
                
                  } // success
              }); // request

          })(eId) // use closure.

        });  // each
  }

2

Answers


  1. Chosen as BEST ANSWER

    I changed my code, and use

     request = $.ajax({
            type: "get",
            url: strURLGet,
            dataType: 'json',    // <- new addition
    
            cache: false,
            complete: function(arrData) { 
                console.log("fSys() complete");             
            },
            success: function(jsonData) {  // Note: Since jQuery 1.8, .success, .error and .complete are deprecated in favor of .done, .fail and .always.
                console.log("fSys() success");
    
                // jsonData is already JSON object. no need to parse it
                // simply use 
                var status = jsonData.status;
                var user = jsonData.user;
                  ...
    

  2. You could try using Promise.all to get all the data then manipulate them, please see this sample code

    First a function to get the ids from DOM nodes

    const getIds = () => {
      const nodes = document.querySelectorAll('.some-class');
      const ids = [...nodes].map(node => node.id.substring('my_obj'.length));
    
      return ids;
    }
    

    Then a function to get the urls given the ids

    const urls = ids => ids.map(id => `http://www.test.com/my_test/get_info.php?p1=p1val&e=${id}`);
    

    Then the function to get the data

    const fetchData = async urls => {
      const responses = await Promise.all(urls.map(url => fetch(url)));
      const json = await Promise.all(responses.map(response => response.json()));
    
      return json;
    }
    

    Finally how to consume the data obtained from calling the previous function

    fetchData(urls).then(json => console.log(json));
    

    I have not tried this code just write based on what is shown in your example,

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search