1

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
  }
15
  • 3
    Why your server gives you the same response for different eid values isn't something we can know. Just check your network tab in Chrome developer tools to make double sure that you're making different requests Commented Dec 19, 2019 at 16:44
  • 2
    it feels like your request variable is global, therefore being override by your second call. So when it reach the success callback, it is not the same as what it was when it started. Commented Dec 19, 2019 at 16:46
  • 3
    Why are you using request.responseText in the first place? Isn't jsonData the response you want? Commented Dec 19, 2019 at 16:48
  • 2
    You can also use dataType: 'json' and jQuery will parse it automatically and put the result in jsonData. Commented Dec 19, 2019 at 17:24
  • 2
    It will also parse it automatically if the server sends Content-type: application/json Commented Dec 19, 2019 at 17:40

2 Answers 2

1

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,

Sign up to request clarification or add additional context in comments.

Comments

0

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;
              ...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.