title: Passing JSON-encoded variable from PHP to Javascript via POST
body: <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>