MrSeth
MrSeth

Reputation: 51

Populating urls into a div from separate directory with Javascript/jquery

My goal is to have users upload photos to a directory in the root called "userupload". All this folder will contain is .jpg images.

I now want to call ALL the image paths from "userupload" directory to a different .php page into a div called "content" like so:<p><img class=resizeme src="userupload/uploadimage1.jpg"></p>

I found this script and I have only been able to return the image file name.. which is fine, but i don't know how edit the code to place it in the correct path.

"This will list all jpg files in the folder you define under url: and append them to a div as a paragraph. Can do it with ul li as well."

$.ajax({
  url: "useupload",
  success: function(data){
     $(data).find("a:contains(.jpg)").each(function(){
        // will loop through 
        var images = $(this).attr("href");

        $('<p></p>').html(images).appendTo('#content')

     });
  }
});

Upvotes: 1

Views: 450

Answers (2)

bfavaretto
bfavaretto

Reputation: 71918

The code you posted seems to rely on the webserver being configured to return a directory index listing for the userupload folder (thus may not work on a different webserver – the proper way to do it on the server-side is what Joseph Silber suggests). The listing consists of links to relative urls.

Considering that what you have already is working, and that all of your images are under userupload, a simple change inside your .each loop should do the trick:

var images = 'userupload/' + this.href;
$('<p><img class="resizeme" src="' + images + '"></p>').appendTo('#content');

Considering your comment that you're getting src="userupload/mysite.com/uploadimage1.jpg":

var images = 'userupload/' + this.href.split('/')[1];
$('<p><img class="resizeme" src="' + images + '"></p>').appendTo('#content');

Upvotes: 0

Joseph Silber
Joseph Silber

Reputation: 219936

Here's the PHP you could use:

image_listing.php:

<?php

$imageLinks = array();
$dh = opendir("userupload");

while ( $file = readdir($dh) )
{
    $tempArray = explode(".",$file);
    if ( isset( $tempArray[1] ) && $tempArray[1] == "jpg" )
    {
        array_push( $imageLinks, 'http://example.com/userupload/' . $file );
    }
}
closedir($dh);

echo json_encode( $imageLinks );

This will return an array of links, which you could then use in your JavaScript:

$.get('image_listing.php', function (array) {
    $.each(array, function(){
         $('#content').append('<p><img class="resizeme" src="' + this + '"></p>');
    });
});

This is a quick example which works, but you should probably build an HTML fragment (instead of hitting the DOM each time in the loop):

$.get('image_listing.php', function (array) {
    var container = $('<div'>);
    $.each(array, function(){
         container.append('<p><img class="resizeme" src="' + this + '"></p>');
    });
    $('#content').append( container.html() );
});

Upvotes: 1

Related Questions