0

In my code I use AJAX to fill an array and that's work perfectly but when I use length for this in outside its giving 0.

Look at this code and the comment show you exactly what I mean.

$.ajax({
        url: "url",
        type : "GET",
        //contentType: "application/json",
        //dataType: "json",
        data : { firstDate : "date1",
                secondDate : "date2"}
                    //student_name : $('#id_student_name').val()
    }).then(function(data) {

        var obj = JSON.parse(data);
        obj.results.forEach(element => {
            console.log(element.DATEEND); 
            res.push(element);
            dates.push(element.DATESTART);
        });

    });
    var days = ['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'];
    var i;

    function min_date(all_dates) {
        var min_dt = all_dates[0],
        min_dtObj = new Date(all_dates[0]);
        all_dates.forEach(function(dt, index){
            if ( new Date( dt ) < min_dtObj)
            {
                min_dt = dt;
                min_dtObj = new Date(dt);
            }
        });
        return min_dt;
    }

    var d = [];
    console.log(res.length + "    "); // this give 0
    for (var a = 0; a < res.length; a++) {
        d[a] = res[a].DATESTART;
        console.log(res[a].DATESTART);
    }
    console.log(d);//this is vide

    console.log(res); //this give all element

.
.
.
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
M.SAM SIM
  • 85
  • 1
  • 5
  • where exactly is problem (in which console statement) . Show more code (context) – Kamil Kiełczewski May 16 '18 at 16:25
  • Did you try to print obj, just to make sure its not empty? – Sailesh Kotha May 16 '18 at 16:27
  • 1
    If you are trying to test the length of the array outside of the ajax method, then you are most likely running into a timing issue and you are checking the array length before the ajax finishes. – Taplar May 16 '18 at 16:34
  • 2
    my guess it has nothing to do with the code above but the Ajax call and where you are logging things. https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron – epascarello May 16 '18 at 16:36
  • look at edit post – M.SAM SIM May 16 '18 at 16:52
  • If you load the page with your console open the entire time (make sure you open the console before you refresh the page), does the last line still log a full array? It looks like you might be opening your console after the code run, and the object logged by the final `console.log` call is showing you the object at the time you opened the console. You could also try `console.log(JSON.stringify(res));` or `console.log(res+"")` to show the array as astring instead of an object. The object is indeed empty when you're logging it, and the log is lying a little bit on the last call. – apsillers May 16 '18 at 16:56
  • Asynchronous code, woo! – Niet the Dark Absol May 16 '18 at 16:56
  • If you log none primitive elements to the console then their reference is stored for logging. Because of that the content of the refernce object might refelct a later state of the object then the time when you did the logging. This [fiddle](https://jsfiddle.net/L7d67w9v/) will have the same behaviour without any async code. – t.niese May 16 '18 at 17:03
  • @Niet the Dark Absol what? – M.SAM SIM May 16 '18 at 17:14

1 Answers1

0

If you log a none primitive element to the console then its reference is stored for logging. Because of that the content shown that is shown in the console might refelct a later state of the object then it had at the time when you did the logging.

This fiddle will have the same behaviour without any async code:

var a = []
console.dir(a.length)
console.dir(a) // the array a does not have any elements a the time 
               // you do the logging but the console will show an
               // array with 10 elements
for (var i = 0; i < 10; i++) {
  a.push(1)
}

You could even extend that to an example like this:

var a = []
console.dir(a.length)
console.dir(a)
for (var i = 0; i < 4; i++) {
  a.push(1)
}
console.dir(a)
for (var i = 0; i < 4; i++) {
  a.push(2)
}

Both logs will show the latest state of the element, not the state at which it was logged. So if you want to see the actual value the element holds you need to either add a break point or a debugger statement right after the logging. Or you need to convert the object into a string.

t.niese
  • 39,256
  • 9
  • 74
  • 101