Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
103
rated 0 times [  109] [ 6]  / answers: 1 / hits: 28126  / 10 Years ago, mon, may 19, 2014, 12:00:00

I'm trying to loop the returning Array from PHP. But jQuery .length is giving me:



'undefined'


PHP:



$items = array();
$items[country] = North Korea,
$items[fruits] = array(
apple=>1.0,
banana=>1.2,
cranberry=>2.0,
);
echo json_encode( $fruits );


jQuery:



$.ajax({
url: items.php,
async: false,
type: POST,
dataType: JSON,
data: { command : getItems }
}).success(function( response ) {
alert( response.fruits.apple );
alert( response.length );
});



  • Here the First Alert() is ok, by returning: 1.0.

  • Then the Second Alert() to detect length response.length is returning:

    • undefined




Then how can i loop this Array (or) how to loop the Fruits (defined by PHP like $items[fruits]) from jQuery end please?


More From » php

 Answers
7

simply try something like this



To do this in any ES5-compatible environment, such as Node, Chrome, IE 9+, FF 4+, or Safari 5+:



alert(Object.keys(response).length); 


your code



$.ajax({
url: items.php,
async: false,
type: POST,
dataType: JSON,
data: { command : getItems }
}).success(function( response ) {
alert( response.fruits.apple );
alert(Object.keys(response).length);
});


REFERENCE



How to efficiently count the number of keys/properties of an object in JavaScript?


[#70946] Friday, May 16, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jarrettw

Total Points: 300
Total Questions: 98
Total Answers: 103

Location: Saudi Arabia
Member since Mon, Sep 5, 2022
2 Years ago
;