I have an multi-dimensional array that I want to send to a PHP script with a Javascript that parses the JSON data and plot it on Google Maps. I'm trying to simulate it using forms:
<?php
$jsontest = array(
0 => array(
'plate_no' => 'abc111',
'longlat' => array(121.003895,14.631563),
'info' => 'first item'
),
1 => array(
'plate_no' => 'abc222',
'longlat' => array(121.103895,14.731563),
'info' => 'second item'
)
);
$jsonarray = json_encode($jsontest);
?>
<form action="json-target.php" method="post" accept-charset="utf-8">
<input type="hidden" name="jsonarray" value="<?php echo $jsonarray; ?>" id="jsonarray">
<p><input type="submit" value="Continue →"></p>
</form>
json-target.php looks like this:
<?php
print "The value of \$_POST is ";
print_r($_POST);
?>
And the output of $_POST
is Array ( [jsonarray] => [{ )
. I wanted to pass the contents of the $jsonarray
variable to a Javascript function (please see update below).
UPDATE: I also have a simple Javascript that's supposed to parse the value received from $_POST
and post the value via alert()
:
<script src="/js/json2.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8">
var json = JSON.parse(<?php echo $_POST['jsonarray'] ?>);
for (var i = 0; i < json.length; i++) {
alert(json[i]);
}
</script>
But the output is mangled with backslash characters.
var json = JSON.parse([{\"plate_no\":\"abc111\",\"longlat\":[121.003895,14.631563],\"info\":\"first item\"},{\"plate_no\":\"abc222\",\"longlat\":[121.103895,14.731563],\"info\":\"second item\"}]);
What's a better way of doing this?