Brainy Prb
Brainy Prb

Reputation: 433

Why is array.length returning me wrong number?

This is my javascript code in which I am calling a php file each 5 seconds ,the php file returns some id's in form of javascript array but array.length is giving me 18 while there are only 2 elements in the array.

PHP file response:

["20","1"]
//function to rotate thumbnails
  window.setInterval(function () {    
            var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                var index;
                var a = xmlhttp.responseText;
                for (index = 0; index < a.length; index++) {
                    pass_value_to_other_function(a[index]);
                }               
            }
        }
        xmlhttp.open("GET", "thumb_rotator.php", true);
        xmlhttp.send();
    }, 5000);

Upvotes: 3

Views: 508

Answers (1)

Simon Farrugia
Simon Farrugia

Reputation: 100

You need to parse the response to a javascript Object/Array.

var a = JSON.parse(xmlhttp.responseText);

Upvotes: 6

Related Questions