bluepinto
bluepinto

Reputation: 165

php json_encode in js returning undesired result

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.

Upvotes: 0

Views: 135

Answers (3)

Alex
Alex

Reputation: 7027

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 );

Upvotes: 0

VolkerK
VolkerK

Reputation: 96159

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; ?>;

Upvotes: 1

Tushar
Tushar

Reputation: 87203

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

Upvotes: 1

Related Questions