I want to display all images from folder located in server in image gallery.
Is there a way to return a list of all the image file names from a folder using only JavaScript or JQuery?
Also I want to count the number of image files in similar folder using only JavaScript.
Is there any way to count the number of image files from a folder using only JavaScript?
No. JavaScript is a client-side technology and cannot do anything on the server. You could however use AJAX to call a server-side script (e.g. PHP) which could return the information you need.
If you want to use AJAX, the easiest way will be to utilise jQuery:
IMHO, Edizkan Adil Ata's idea is actually the most proper way. It extracts the URLs of anchor tags and puts them in a different tag. And if you don't want to let the anchors being seen by the page visitor then just
.hide()
them all with JQuery ordisplay: none;
in CSS.Also you can perform prefetching, like this:
That way you don't have to hide it and still can extract the path to the image.
No, you can't do this using Javascript alone. Client-side Javascript cannot read the contents of a directory the way I think you're asking about.
However, if you're able to add an index page to (or configure your web server to show an index page for) the images directory and you're serving the Javascript from the same server then you could make an AJAX call to fetch the index and then parse it.
i.e.
1) Enable indexes in Apache for the relevant directory on yoursite.com:
http://www.cyberciti.biz/faq/enabling-apache-file-directory-indexing/
2) Then fetch / parse it with jQuery. You'll have to work out how best to scrape the page and there's almost certainly a more efficient way of fetching the entire list, but an example:
This will list all
jpg
files in the folder you define under url: and append them to adiv
as a paragraph. Can do it withul li
as well.Many tricks work, but the Ajax request split the file name at 19 characters? Look at the output of the ajax request to see that:
The file name is okay to go into the href attribute, but the
$(this).attr("href")
use the text of the<a href='full/file/name' >
Split file name</a>
So the
$(data).find("a:contains(.jpg)")
is not able to detect the extension.I hope this is useful
Although you can run FTP commands using WebSockets, the simpler solution is listing your files using
opendir
in server side (PHP
), and "spitting" it into the HTML source-code, so it will be available to client side.The following code will do just that,
Optionally -
<a>
tag to present a link.query for more information using server side (
PHP
),for example a file size,
PHP filesize TIP: also you can easily overcome the 2GB limit of PHP's filesize using: AJAX + HEAD request + .htaccess rule to allow
Content-Length
access from client-side.A Fully Working example can be found at my github repository:
download.eladkarako.com
The following is a trimmed-down (simplified) example:
DOM result will look like that: