0

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?

3
  • 5
    Have you taken a look at the generated JavaScript code? Commented Jul 2, 2013 at 18:45
  • What does the actual HTML/JavaScript look like when the page is rendered? Commented Jul 2, 2013 at 18:46
  • Oh dear, I need some sleep. Thank you. Commented Jul 2, 2013 at 18:51

3 Answers 3

2

numArray v.s. numtArray. Notice the extra t... you're not assigning your array, you're assigning an undefined variable, producing a null.

Sign up to request clarification or add additional context in comments.

Comments

0
var jsonText = "<?php echo json_encode($json); ?>";
var jsonData = JSON.parse(jsonText);
console.log(jsonData['num'].length);

Comments

0

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.

1 Comment

In your JavaScript code, var json is not a string, so you don't need JSON.parse. JSON can be evaluated as JavaScript code, so var json is already an object, no parsing needed. If you did var json="<?php echo $json; ?>";, then you'd need to parse it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.