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

4
  • stackoverflow.com/questions/16202712/… Commented Jan 1, 2014 at 11:04
  • Are you want to access php variable in jquery ? Commented Jan 1, 2014 at 11:04
  • 1
    The question Why comes to mind. Unless you ajax the php created JSON, why not just use the php to write the image tags? Commented Jan 1, 2014 at 11:06
  • @mplungjan i did this: echo '<img src="/uploads/'.json_encode($images).'"/>'; and it fails to find the images. When i right click the blank image and try to save it, it gives me "[.htm" Commented Jan 1, 2014 at 11:17

3 Answers 3

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 + '"/>');
    });
});
Sign up to request clarification or add additional context in comments.

Comments

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";
}

Comments

-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>

1 Comment

No need whatsoever to encode that string nor to put it in quotes in the script nor to use jQuery

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.