Note that there are some explanatory texts on larger screens.

plurals
  1. POPassing JSON-encoded variable from PHP to Javascript via POST
    primarykey
    data
    text
    <p>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:</p> <pre><code>&lt;?php $jsontest = array( 0 =&gt; array( 'plate_no' =&gt; 'abc111', 'longlat' =&gt; array(121.003895,14.631563), 'info' =&gt; 'first item' ), 1 =&gt; array( 'plate_no' =&gt; 'abc222', 'longlat' =&gt; array(121.103895,14.731563), 'info' =&gt; 'second item' ) ); $jsonarray = json_encode($jsontest); ?&gt; &lt;form action="json-target.php" method="post" accept-charset="utf-8"&gt; &lt;input type="hidden" name="jsonarray" value="&lt;?php echo $jsonarray; ?&gt;" id="jsonarray"&gt; &lt;p&gt;&lt;input type="submit" value="Continue &amp;rarr;"&gt;&lt;/p&gt; &lt;/form&gt; </code></pre> <p>json-target.php looks like this:</p> <pre><code>&lt;?php print "The value of \$_POST is "; print_r($_POST); ?&gt; </code></pre> <p>And the output of <code>$_POST</code> is <code>Array ( [jsonarray] =&gt; [{ )</code>. I wanted to pass the contents of the <code>$jsonarray</code> variable to a Javascript function (please see update below).</p> <p><strong>UPDATE:</strong> I also have a simple Javascript that's supposed to parse the value received from <code>$_POST</code> and post the value via <code>alert()</code>:</p> <pre><code>&lt;script src="/js/json2.js" type="text/javascript" charset="utf-8"&gt;&lt;/script&gt; &lt;script type="text/javascript" charset="utf-8"&gt; var json = JSON.parse(&lt;?php echo $_POST['jsonarray'] ?&gt;); for (var i = 0; i &lt; json.length; i++) { alert(json[i]); } &lt;/script&gt; </code></pre> <p>But the output is mangled with backslash characters.</p> <pre><code>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\"}]); </code></pre> <p>What's a better way of doing this?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload