Page 1 of 1

insert php element into java script array

Posted: Mon Nov 08, 2010 12:05 am
by priyanka01
Hi,

Code: Select all

      path=new Array();
      path[0]="<?= $field[0] ?>";
       path[1]="<?= $field[1] ?>";
i want to insert it in loop for example

Code: Select all

     path=new Array();
for (var i=0;i<path.length;i++){
  path[i]="<?= $field[i] ?>"; // but its not working

}
but the above code is not working please tell me another way

Re: insert php element into java script array

Posted: Mon Nov 08, 2010 3:16 am
by Christopher
You cannot do the second one because $field will only equal one value when you generate the Javascript. Either use the first method, or try generating JSON.

Re: insert php element into java script array

Posted: Mon Nov 08, 2010 10:05 am
by Jonah Bron
Or this (untested)

Code: Select all

var path = ["<?php echo implode('", "', $field); ?>"];

Re: insert php element into java script array

Posted: Mon Nov 08, 2010 10:16 am
by Weirdan
Jonah Bron wrote:Or this (untested)

Code: Select all

var path = ["<?php echo implode('", "', $field); ?>"];
json_encode is almost always better:

Code: Select all

var path = <?php echo json_encode($field);?>;