I am trying to get the values of PHP Array in JavaScript variable. Here is my code:
$qry="select * from optin";
$rlt1=mysql_query($qry);
$em_ary=array();
while($row= mysql_fetch_array($rlt1)){
$em_ary=$row;
echo $em_ary['timer'];}// this echo show all records that I have in data base and I want to get all the values in Javascript
<script>
var tmr=[];
tmr='<?php echo json_encode($em_ary['timer']); ?>';
alert(tmr);// this alert only shows the last record in the database
<?script>
Where I am going wrong or is there any other way to accomplish this? Thanks in advance!
You are overwriting values within your $em_ary
array in order to make an array of values you need to place []
after $em_ary
which will result you an array
$em_ary[]=$row;
You need to update this also from
tmr='<?php echo json_encode($em_ary['timer']); ?>';
into
tmr="<?php echo json_encode({$em_ary['timer']}); ?>";
You need to update this line:
$em_ary = $row;
and change it to:
$em_ary[] = $row;
You are overwriting the array each time you want to add a new element to it.
Then, in the JS part, update this line:
tmr = '<?php echo json_encode($em_ary['timer']); ?>';
to:
tmr = JSON.parse('<?php echo json_encode($em_ary); ?>');
Hope this helps! Cheers!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.