user1869730 user1869730 - 2 months ago 10
HTML Question

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

Using PHP version 5.6, the code for the php is

$dir = "uploads/image/dashed/";
$files = scandir($dir);
foreach ($files as $file)
{
if ( is_file($dir. $file) ){
echo $file;
}
}


the ajax response code is:

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


all I keep getting from the server is
1354876944ABF.jpg_MG_0085.jpg
and an empty image place holder (not two, just the one) for where the image
and the image address is showing two image names stuck together in one link


uploads/image/dashed/1354876944ABF.jpg_MG_0085.jpg


where the response link should be on two (for this example) different lines and images where the is on the html inside the ajax call

Answer

Try This,

$dir = "uploads/image/dashed/";
$files = scandir($dir);
$i = 1;
$count = count($files);
foreach ($files as $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

Comments