Note that there are some explanatory texts on larger screens.

plurals
  1. POPassing PHP array to Javascript array using implode(), join() or json_encode()
    text
    copied!<p>I am working on a Wordpress plugin and I need to pass PHP array to Javascript array. I have tried using join(), implode() and even Json_encode. But, the wordpress is not displaying any value.</p> <p>When using join(), I used the code:</p> <pre><code>&lt;?php $php1 = array(1,2,3); ?&gt; &lt;script language='Javascript'&gt; var lat = ["&lt;?php echo join("\", \"", $php1); ?&gt;"]; document.write(lat[1]); &lt;/script&gt; </code></pre> <p>If used on localhost(without wordpress), the above code provides a valid output. But, somehow, its not working on Wordpress. The "apache error log" show this message:</p> <p>PHP Warning: join() [function.join]: Invalid arguments passed in \wp-content\plugins\Animation\animation.php on line 129, referer: <a href="http://localhost/Website/wp-admin/options-general.php?page=js" rel="nofollow">http://localhost/Website/wp-admin/options-general.php?page=js</a></p> <p>Same is the case with implode(). Server error log shows same above warning for implode().</p> <p>Then I tried for json_encode using the code below:</p> <pre><code>var lat = &lt;?php echo json_encode($php1); ?&gt;; </code></pre> <p>But the no value is returned.</p> <p>Edit: Code I used for JSON:</p> <pre><code>&lt;?php /* Plugin Name: PHPToJavascript */ $arr = array(1,2,3,4,5,6,7,8,9); //array to pass add_action('admin_menu','admin_jav'); function admin_jav(){ add_submenu_page('options-general.php','Javarray','Javarray','manage_options','javarray',jav_handler); } function jav_handler(){ echo 'Into handler'; ?&gt; &lt;SCRIPT LANGUAGE = 'Javascript'&gt;&lt;!-- var sm=&lt;?php echo json_encode($arr); ?&gt;; //using Json document.write(sm[1]); //doesnt display any output!!! &lt;/SCRIPT&gt; &lt;?php } ?&gt; </code></pre> <p>Please guide me through this. I appreciate any help. It would be great if you help me in passing this PHP array to javascript array.</p>
 

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