0
    <?php
$imgDir =   'images/';
$images =   glob($imgDir . '*.{jpg,jpeg,png,gif}',GLOB_BRACE);
echo json_encode($images);  
?>

<script>
jQuery(function(){
    var phpvar  =   '<?php echo json_encode($images) ?>';
        jQuery('body').append('<img src="' + phpvar + '"/>');
    });
</script>

The top php scans the folder 'images' and echoes all the file pathnames. However i want to use the array formed from this and append it to the document/body to display the images using . But i'm not sure how to pass the php variable '$images' to jquery/javascript

jn025
  • 2,755
  • 6
  • 38
  • 73

3 Answers3

1

The phpvar that you're creating is actually an array (provided you remove the quotes), so you need to loop through this array and add each image separately, like this:

jQuery(function(){
    var phpvar = <?php echo json_encode($images) ?>;
    $.each(phpvar, function(id, image){
        jQuery('body').append('<img src="' + image + '"/>');
    });
});
duellsy
  • 8,497
  • 2
  • 36
  • 60
1

In my opinion you are wasting processing and a needless framework for simple PHP array processing.

No need for either JSON, JSONEncode or jQuery:

foreach (glob('images/*.{jpg,jpeg,png,gif}',GLOB_BRACE) as $filename) {
  echo '<img src=".$filename.'" alt="" />'."\n";
}
mplungjan
  • 169,008
  • 28
  • 173
  • 236
-1
<?php
$imgDir =   'images/';
$images =   glob($imgDir . '*.{jpg,jpeg,png,gif}',GLOB_BRACE);
$image_var ="";
foreach($images as $img)
{
$image_var.="<img src=".$img.">";
}

echo json_encode($image_var);
?>

<script>
jQuery(function(){
var phpvar  =   <?php echo json_encode($image_var) ?>;
    jQuery('body').append(phpvar);
});
</script>