0

I'm trying to pass an array from php to JavaScript. But in js the array values are being read as each individual char. My code;

<?php
$arr=array(1=>'apple', 2=>'ball');
$garr=json_encode($arr);
?>

<script>
var ax = '<?php echo $garr; ?>';
alert(ax.length);
for(var n=0;n<ax.length; n++)alert(ax[n]);
</script>

The result is lenght=23 and each char as output.

Thank you for your help.

3 Answers 3

1

Because ax is string. You need to convert the string representation in json format. Use JSON.parse to convert string to json.

The JSON.parse() method parses a string as JSON, optionally transforming the value produced by parsing.

var ax = JSON.parse('<?php echo $garr; ?>'); // ax is not JSON object
Sign up to request clarification or add additional context in comments.

1 Comment

both you and @VolkerK are right. needed json.parse AND not return object
1

The output of json_encode() for your php array is

{"1":"apple","2":"ball"}

that's an object literal. But you want an array. Try it with:

$arr=array(0=>'apple', 1=>'ball');

And remove the single-quotes, they mark a string literal and you don't want ax to be a string but an array/object.

var ax = <?php echo $garr; ?>;

Comments

0

You're just printing a JSON string, this way ax will be nothing more than a string.

Use a parser, see here:

var jsontext = '{"firstname":"Jesper","surname":"Aaberg","phone":["555-0100","555-0120"]}';
var contact = JSON.parse(jsontext);

If you're using JQuery use this:

jQuery.parseJSON( jsonString );

1 Comment

Reverse is str = JSON.stringify(obj);

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.