Skip to content Skip to sidebar Skip to footer

Displaying Multiple Images With An Ajax Response

I am trying to display multiple images coming from a remote server on a single page, the page is a html file where putting php blocks wouldn't be doing anything to get thing I want

Solution 1:

Try This,

$dir = "uploads/image/dashed/";
$files = scandir($dir);
$i = 1;
$count = count($files);
foreach ($filesas$file){

if(is_file($dir. $file)){
if($i == $count){
echo$file;
}else{echo$file.'|||';
   }
  }
$i++;}

and change ajax to:

$(document).ready(function(){
    $.ajax({
        async: true,
        type: 'POST',
        url: 'folder.php',
        success: function(data){
           $("#imageContent").html(data).append("<br/>");
           var images = data.split("|||");
            for (var i = 0, j = images.length; i < j; i++){
               $("#imageContent").append("<img src='uploads/image/dashed/" + images[i] + "' width='300'>"); 
            }
        }
    });
});

thats using ||| as a delimiter.

EDIT: now it should work properly, EDIT2: changed $i = 0 order, added $i++; at the end

Solution 2:

scandir() is already giving you an array, so why not just json_encode it and return this? unset() any output that is not a valid file:

$files = scandir($dir);
$count = count($files);

for($i = 0; $i < $count; $i++) {
    if ( !is_file($dir. $file) ){
        unset($files[$i]);        
    }
}

echo json_encode($files);

then in your success block:

success: function(data){
           $("#imageContent").html(data).append("<br/>");
           var i,
               json = JSON.parse(data);          
           for (i in json){
               $("#imageContent").append("<img src='uploads/image/dashed/" + json[i] + "' width='300'>"); 
            }
        }

Post a Comment for "Displaying Multiple Images With An Ajax Response"