Search code examples
javascriptjquerygetjson

$.getJSON with for loop, just working when debugging


**I really need help, because I´m not able to find a working solution or do it by my self. The problem is, that I can´t get the information. "data" should include 23 objects. The thing is, while debugging everything works well. Please help me!!! I am nearly on my end. and Callback or then.(function...) are not working for me... ;( **

function query_day2day(DateArray_){

        var Fluid_id = 0;
        var data_list = new Array();

    //read out the select element
        var e = document.getElementById("select_fluid");
        var Fluid_id = e.options[e.selectedIndex].value;
    //read in date
        //var d = document.getElementById("datepicker");
        //var date = d.value;
        var dateArray = new Array();
        dateArray = DateArray_;
    //Bring the date array in the correct form to submit
        for(i = 0; i<dateArray.length; i++)
        {
        var year = dateArray[i].substring(6, 10);   //substring(start, end)
        var month = dateArray[i].substring(0, 2); 
        var day = dateArray[i].substring(3, 5);  

        dateArray[i] = year + "-" + month + "-" + day;
        //alert(dateArray[i]);
        }

        for(i = 0; i<dateArray.length; i++)
        {
        switch (Fluid_id) {
            case '1':
               $.getJSON(setAddress_Event() + 'liter_hour/' + Fluid_id + '/' + dateArray[i], function(data){


                //data_callback(data, i); //I don´t understand this concept ;(
               data_list[i] = data;     


                });
                break;
            case '2':
               $.getJSON

Updated

        function getData(setAddress_Event, liter_hour, Fluid_id, dateArray){
          return $.getJSON(setAddress_Event + liter_hour + Fluid_id + "/" + dateArray).then(function(data){
            return {
              data_list:data
            }
          });
        }

        for(var j = 0; j<dateArray.length; j++)
        {
        getData(setAddress_Event(), "liter_hour/", Fluid_id, dateArray[j]).then(function(returndata){
          //received data!
          alert(j);
          data_collection[j] = returndata;

        });

        }


    alert(data_collection); //Hier ist data_list undefined und beim returnen wird es richtig übergeben.... ohne diesem alert wird falsch übergeben.... dreck
    return data_collection;

Please help me, I need all data not just the last one. Debugging works, I don´t know what´s here the problem....

Debugg Snippet


Solution

  • This is because you are accessing the data before the Ajax requests for retrieving the JSON have sent back the responses. Be aware that when you execute

        getData(setAddress_Event(), "liter_hour/", Fluid_id, dateArray[j]).then(function(returndata){
          //received data!
          alert(j);
          data_collection[j] = returndata;
        });
    

    ... the inner function is not executed. It is only passed on to getData, and your code continues immediately. Only when the execution reached the end of the script, will the Ajax requests one by one call your callback function, so they all execute after the main scripts ends.

    Here is how you could deal with that (introducing a variable numPendingResults):

    var numPendingResults = dateArray.length;
    for(let j = 0; j<dateArray.length; j++) {
        getData(setAddress_Event(), "liter_hour/", Fluid_id, 
                                    dateArray[j]).then(function(returndata){
          //received data!
          data_collection[j] = returndata;
          numPendingResults--; // one less to wait for!
          if (!numPendingResults) { // we have everything!
            console.log(data_collection);
            // anything you want to do with data_collection should be done here
            // ...
            // or call a function that will deal with it, from here.
          }
        });
    }
    

    You cannot return the data_collection. Instead you should call a function like described above. Possibly that function can be passed as argument by the outermost function. Or use the Promise system one step further. For you to decide...