Reputation: 492
I have an array in PHP.
$numArray=array("1","2","3","4");
I want to transfer this array to javascript along with other data. I do the following-
$json = array(
'num' => $numtArray
);
In javascript I do the following.
var json=<?php echo json_encode($json); ?>;
console.log(json['num'].length);
I get undefined in console. How do I find length of this array?
Upvotes: 0
Views: 849
Reputation: 3294
To transfer to json u need to encode your data, like this:
$json = array(
'num' => $numtArray
);
$json = json_encode($json);
In JavaScript you need to parse json string
var json=<?php echo $json; ?>;
console.log(JSON.parse(json));
what is that show you? It seems to be an object with key 'num', which is an array you looking for.
I hope that will help you.
Upvotes: 0
Reputation: 12939
var jsonText = "<?php echo json_encode($json); ?>";
var jsonData = JSON.parse(jsonText);
console.log(jsonData['num'].length);
Upvotes: 0
Reputation: 360632
numArray
v.s. numtArray
. Notice the extra t
... you're not assigning your array, you're assigning an undefined variable, producing a null.
Upvotes: 2