0

**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

2 Answers 2

1

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

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

7 Comments

Thank you a lot for your nicely done comment!!! Such an professional solution :) But I have still nearly the same problem. If the for loop is done, this is in the console.log: Array [ < 3 free positions>, Object ] In the object is the data from today, the 3 objects before are not here. ??
Indeed there is an issue. By the time the then-callbacks execute, the j variable has already reached the array length, and so results are all stored in the same array element. One way to fix it is to declare the loop-variable j with let instead of var. That way each iteration has its own instance of j. I adapted the code accordingly.
As I said, you are the King! It works. If i could i would give you 100 votes, but unfortunately I am not able to do one?? ^^ Array [ Object, Object, Object, Object, Object ]!!!!!!! YES
why is it not possible to return data_collection? I got stuck with this, because when I make a function in which i call the data function, I cannot work with the date directly. Again debugging is possible ... OMG :) collection = query_day2day(DateArray_);
Not sure what you mean. If you still have questions about this, I suggest you read a bit about asynchronous Javascript, for instance here.
|
0

Try something similar to this. You may need to loop through the elements in order to use them.

                $.getJSON('/ReferenceData/PhoneType',
            function (data) {
                if (!isBound) {
                    dropDownToBind.append($('<option></option>').val(-1).html('- Select Type -'));
                    $.each(data, function (index, element) {
                        dropDownToBind.append($('<option></option>').val(element['Id']).html(element['Value']));
                    });
                    isBound = true;
                }
            });

// OR this

                                $.getJSON(url, params, function (data) {
                                    if (data != null) {
                                        zip_code_field.closest('.formCol').find('.ZipCity').val(data.City);
                                        zip_code_field.closest('.formCol').find('.ZipState').val(data.State);

                                        $.uniform.update();
                                    }
                                });

1 Comment

thx. for the fast comment. I think there is just a timing problem because of asynchronous data transfer... Its enough for today. i go home. My head burns.... see ya

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.