0

Hi I have a php script that successfully gets an array of data from an exsternal xml source, the array is called $file, I know that the php array is populated by using print_r($file).

I have tried to use the following php to pass to a javascript session:

//Convert to JSON Array
$jsonarray = json_encode($file, JSON_FORCE_OBJECT);
$result["json_array"]=$jsonarray;

But either this hasn't worked, or the following JS code below is wrong:

var jsonarray = result["json_array"];

alert(JSON.stringify(jsonarray));

Could someone please tell me where I am going wrong?

2
  • Are you mixing PHP and JS variables? Commented Nov 18, 2014 at 19:11
  • In addition, you may want to use console.log() as opposed to alert. It'll give you more information about what is contained in the object being passed to it - especially if you are dealing with arrays. Commented Nov 18, 2014 at 19:12

2 Answers 2

1

You should not use JSON.stringify there. JSON.parse is what you are looking for. Since you want to parse existing JSON, not create new JSON.

edit: Your code is a bit odd. I'd think you want something like this

php

//Convert to JSON Array
echo json_encode($file, JSON_FORCE_OBJECT);

js

alert(JSON.parse(data)); // Where data is the contents you've fetched from the server
Sign up to request clarification or add additional context in comments.

Comments

0

You have to encapsulate php code :

<?php
$jsonarray = json_encode($file, JSON_FORCE_OBJECT);
$result["json_array"]=$jsonarray;
?>

var jsonarray = <?= $result["json_array"] ?>;

alert(JSON.parse(jsonarray));

Comments

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.