dimanche 12 juin 2016

js get php variable with dynamic name

I have a simple button calling a js function. There I want use the php var with dynamic names. Any Idea please?

<?php 
    $counter = 1;
    ${"fotos" . $counter++} = array(); 
    foreach ($row as $item) {
      ${"fotos" . $counter}[] = $item->img;
    }
 ?>; 
//will generate two vars:
       $fotos  = [img1];
       $fotos1 = [img1,img2];

<button type="button" onClick="verAdjuntos(<?php echo $counter; ?>)" class="btn btn-xs    btn-default"> View</button>
//parameter passed verAdjuntos(1) forxample

When id parameter is null, the if condition works fine. But adding id to php var name is the problem...

<script type="text/javascript">
  function verAdjuntos(id){
    if (id == null){
      var fotos  = <?php echo $fotos ?>; //output ok
      alert(JSON.stringify(fotos));
    }else{
      var fotos  = <?php echo  $fotos?> + id; /// how do name $fotos1 here?
      alert(JSON.stringify(fotos));
   };
  }
</script>

Doing alert work fine too:

alert(JSON.stringify(fotos1)); 

Aucun commentaire:

Enregistrer un commentaire