john
john

Reputation: 71

Using javascript, load images names from a folder to an array

On buttonclick, load images names from a folder to an array in jQuery.

I have code which loads images into the body.

I have a folder named images2 with 20 images in it.

I have an index.html file where folder images2 is located.

I want to convert the code in such a way that, on button click, it loads the names of images to array imagenames.

imagenames[];

function loadimagenames()
{
var folder = "images2/";

$.ajax({
    url : folder,
    success: function (data) {
        $(data).find("a").attr("href", function (i, val) {
            if( val.match(/\.(jpe?g|png|gif)$/) ) { 
                $("body").append( "<img src='"+ folder + val +"'>" );
            } 
        });
    }
});

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="loadimagenames();">loadimage to array</button>

Upvotes: 3

Views: 2554

Answers (2)

Leander
Leander

Reputation: 148

Javascript is being executed client-side and doesn't have access to the local filesystem due to security. Instead of doing an ajax request to the folder you should write a server-side code that glob's trough the given folder and returns the images in it in JSON format.

For example:

<?php
function findImagesInFolder()
{
    $folder = $_GET['folder'];
    $images = glob($folder . '/*.{png,jpg,jpeg,gif}', GLOB_BRACE);

    echo json_encode($images);
    exit();
}

Upvotes: 1

cssyphus
cssyphus

Reputation: 40038

As Nagaraju said, we see you are issuing an ajax call to request the file names -- what is your back-end language? The purpose of AJAX is to send a request to the back-end (server-side) language to do something, and then receive new data back (as a response) that it can then add to the web page. It is the server-side language, however, that actually reads the names of all the image files and returns that list back to the javascript (client) side.

Most servers have PHP available - is that your case? If so, you need to use PHP to request the list of filenames from the folder and return that back to javascript in the ajax.done() method.

If you are doing this locally, then you might need to install something like xampp (comes in versions for Windows, Mac and Linux), which includes apache server (for showing the website) and PHP and MySQL etc. - a full webserver suite, very similar to what you would get from a hosting plan at Namecheap or GoDaddy.

Here is a tutorial for doing what you wish in PHP

Note that with xampp, it creates a folder structure under C:\XAMPP - and your website files are in C:\XAMPP\HTDOCS.

Also note that after installing xampp, open your browser and in the address bar, just type localhost - that is all, just that (and press Enter). The default example website will be displayed on your local machine - the file C:\xampp\htdocs\index.html - try editing that file and refresh the page...

Also note that you can create subfolders under c:\xampp\htdocs for different "sites" - for example, create a simple test site as c:\xampp\htdocs\bob\index.html and then view it in your browser as localhost/bob

Update:

If you really want to use javascript to write your image gallery app, then you still need a server-side language... so you can install node.js. As others pointed out above, javascript itself only works client-side, in the browser, with no access to the file system. HOWEVER, Node.js installs javascript onto the server side, with full access to the webserver's (eg. xampp's) file system.

Here is a tutorial for installing node.js on your xampp installation.

Update 2:

Final note: the amount of PHP you need to learn to use it to write such an application is NOT THAT MUCH. It's very similar to javascript, except:

1) Your .html files must be renamed to .php (you can do this as a matter of course with ALL your .html files from now on... I've never yet encountered a webserver that does not have PHP, and that's after using dozens of different webserver / hosting configurations for scads of clients). Try it now: just rename your index.html to index.php and refresh - still works the same. The only difference is that now you can do (2) below.

2) Within the .php file, it is just an .html file that can now process any PHP code. PHP code is always delineated by <?php //your code goes here ?> tags.

3) All variables - ALWAYS - begin with $. For eg: $var = 'bob'; or $x = 1; or if($x=='bob'){ echo 'Hello<br>';}

4) EVERY STATEMENT must end with a ;. It is not forgiving like javascript. A single missing semi-colon will crash your code.

5) When code crashes, it just crashes. There is no error message returned to the DevTools console... UNLESS you install the PHPConsole browser extension!

6) Install the PHPConsole browser extension.

That's about all you need to know. Now, go program in PHP. You will find it very, very similar to javascript - like Australian v.s. American english.

Upvotes: 2

Related Questions