Reputation: 10571
In php I am sending an array
back to ajax
on front end:
echo json_encode($totSaved);
Then on the front end I do:
...
success: function(data) {
setTimeout(function(){
console.log(data);
console.log(data.length);
...
Console:
console.log(data); = ["128545","128545"]
console.log(data.length); = 19
It should be giving me 2, what am I doing wrong?
Upvotes: 2
Views: 6917
Reputation: 337560
As the result is 19
it seems that data
is a string, not an array. As such you need to parse it, which you can do with JSON.parse()
:
success: function(data) {
setTimeout(function() {
var arr = JSON.parse(data);
console.log(arr);
console.log(arr.length);
}, /* timeout delay */);
});
If you are always expecting a JSON response you could instead set the dataType
property in the AJAX request settings to 'json'
. That way jQuery will parse the response for you.
Upvotes: 5