Jump to content

pass a php array into js

Recommended Posts

Hi all !

This following code is supposed to pass an array from php to js:-

$( document ).ready(function(){
	var rs = <?php echo json_encode($rs);?>;

instead javascript gives an error as 


testsums.js:3 Uncaught SyntaxError: Unexpected token <

Here's the simple php code as well:

	$rs = [[1,2,3],[2,3,4],[3,4,5]];
	// $rs = json_encode($rs);		// This doesn't work either.

Please can someone point out the cause of error here. 

Thanks !


Share this post

Link to post
Share on other sites

Use a hidden field

    $rs = [[1,2,3],[2,3,4],[3,4,5]];
    $jrs = json_encode($rs);
    echo "<input id='rs' type='hidden' value='$jrs'>";


  <script type="text/javascript">
      $().ready( function() {
          var rs = JSON.parse( $("#rs").val() )
          alert( rs[2][0] )                         // 3


  • Thanks 1

Share this post

Link to post
Share on other sites

Thank you Guru Barand !

While the above works fine when the js is enclosed in <script> tags and appended to the php file, it fails when the JS code is included as a separate js file. 

I guess the only way it works when the JS code is in its own file is as indicated by you, using a hidden field ! 

Thank you very much ! 

Share this post

Link to post
Share on other sites

Trying to inject code directly into JS like in your original post is risky.  Someone may be able to use it to inject html/js into the document.  The better approach is to insert the JSON data into your HTML document (with normal HTML escaping applied) and then parse it.  A hidden input is one way to do that, another way is with a data attribute which is what I typically do (jQuery will auto-parse json data attributes).

<script src="/js/something.js" data-rs="[[1,2,3],[2,3,4],[3,4,5]]"></script>
var rs = $(document.currentScript).data('rs');

document.currentScript needs to be read during the initial script load, you can't put it in an event handler for example.  According to caniuse.com, it also doesn't work in IE. If that's a concern, there are alternative methods / polyfills that exist.


  • Like 1

Share this post

Link to post
Share on other sites

Thanks kicken ! for this alternate method. I do not fully understand it, but i'll look it up and if need be reopen this thread again. For the time being I have used the hidden field method suggested by Guru Barand !

Thanks loads !

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now


Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.