0

I am trying to display images on a webpage as a gallery but i only want albums, each folder is an album and you select the album with the link menu so i parse the path to a function that then should then run a php script to return all the names of the images in that album, so far this is what i have.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2 /jquery.min.js"></script>
<div id="content-container" style="height: 500px;">
  <div id="content" style="height: 500px;">
    <div style="float: left; width: 200px;">
      <h1> <span>The Gallery</span> </h1>
      <ul id="nav">
        <li><a href="" id="here">Gallery</a>
          <ul>
            <li><a href="" data-albumid="images/gallery/fld01">photos</a>
            </li>
            <li><a href="" data-albumid="images/gallery/fld02">photos</a>
            </li>
            <li><a href="" data-albumid="images/gallery/fld03">photos</a>
            </li>
            <li><a href="" data-albumid="images/gallery/fld04">photos</a>
            </li>
          </ul>
        </li>
        <li><a href="index.html">Back to home</a>
        </li>
      </ul>
    </div>
    <div class="album-container"></div>
    <script type="text/javascript">
      $(document).ready(function() {
        $("a").click(function() {
          var id = $(this).data("albumid");
          $(".album-container").empty();
          LoadGallery(id);
          return false;
        });
      });

      function LoadGallery(id) {
          alert('Loading gallery #' + id);
          $(".album-container").load("getimages.php?dirpath=id,function() {
            var reciverParameters = $(".album - container ").html();
            var parser = new Array();
            parser = reciverParameters.split(", ");
            alert(parser);
            })
            /*
            var curimg=0

            function rotateimages(){
                document.getElementById("
              album - container ").setAttribute("
              id "+galleryarray[curimg]);
                curimg=(curimg<galleryarray.length-1)? curimg+1 : 0;
            }

            window.onload=function(){
                setInterval("
              rotateimages()
              ", 2500)
            }
            })
            */
        }
    </script>
    <div class="clear"></div>
  </div>
</div>

PHP:

<?
//PHP SCRIPT: getimages.php
Header("content-type: application/x-javascript");
$dirname = $_get['dirpath'];

function returnimages($dirname) {
    $pattern="(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$)";
    $files = array();
    $curimage=0;
    if($handle = opendir($dirname)) {
        while(false !== ($file = readdir($handle))){
            if(eregi($pattern, $file)){ //if this file is a valid image
                //Output it as a JavaScript array element
                echo 'galleryarray['.$curimage.']="'.$file .'";';
                $curimage++;
            }
        }

        closedir($handle);
    }
    return($files);
}

echo 'var galleryarray=new Array();'; //Define array in JavaScript
returnimages() //Output the array elements containing the image file names
?>
2
  • Try using Ajax, in jQuery, $.post( url ... ) or $.get( url ... ) Commented Nov 18, 2015 at 19:05
  • I am new to this and i am not sure how to implement your suggestion, sorry Commented Nov 18, 2015 at 19:08

1 Answer 1

2

You should make some change in both the php and html code.

PHP Code

First of all change the tag <? to <?php.

The most important change: change the format in which you send the image list to the client. Instead of sending JavaScript, send JSON, which is intended for this kind of stuff.

To do that, change the Header call to this:

header('Content-Type: application/json');

Then in the function returnimages, replace the echo line with:

$files[] = $dirname . "/" . $file;

This will collect the images in the $files array, and that will be returned by the function. Note that you should prefix the file name with the directory name, to have a qualified reference. Also note you don't actually need the $curimage variable, because with the $files[] notation, you indicate that elements should be added at the end of the array.

This function relies on eregi which is deprecated since php 5.3. Instead you could use preg_match. For that you need to put slashes around your regular expression, like this:

$pattern="/(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$)/";

Then, replace the test with this:

if (1 === preg_match($pattern, $file)) {

The function's return value should be converted to JSON -- this should be the only thing you echo:

echo json_encode(returnimages($dirname));

Note that in your original code, you did not pass the $dirname argument, so it could not have worked.

This will make PHP return a JSON encoded array, which is so much better than sending back a piece of JavaScript.

HTML Code

Here you need to change the $(".album-container").load call by the following:

$.getJSON('getimages.php', {dirpath: id}, function(galleryarray) {
    var galleryHtml = [];
    // Go through each element in the returned array (galleryarray) 
    // and build image tags for them
    $.each(galleryarray, function (index, file) {
        // TODO: Add any other `HTML` you need with this image tag
        galleryHtml.push('<img src="' + file + '"/>');
    }):
    // Now put these images inside the container.
    $(".album-container").html(galleryHtml.join(''));
});

If this looks all new to you, please read a bit about the php json_encode function, and maybe even about json in general. Also read about the jQuery.getJSON method to understand each parameter and the asynchronous nature of such methods. These pages have examples which should help you further.

Maybe the file references of your images need to be prefixed with some folder... I don't know where you have them stored. But this you can encode in the img tags, and maybe you want to add some other html or css stuff there.

Once the above code works, you will probably want to do more. But this should be the way to move forward.

Sign up to request clarification or add additional context in comments.

25 Comments

Having followed your code and implemented it in to mine it shows no errors but still no images, not to sure what is wrong.
Have you debugged with console.log? I did not test the code, it is just pointing in the right direction. For instance, add console.log(galleryarray); in the JS function I provided above, and see what it reports.
Another thing you can do to debug, is call getimages.php?dirpath=images/gallery/fld01 directly in your browser (prefix with http:// ... etc) and see if you get the JSON output displayed.
I am getting galleryarray not defined error, so looking at the code should Var galleryhtm = []; read galleryarray = []; ?
Having added Var galleryarray = []; that error has gone but now it's showing "not well formed" and is pointing to the path i sending to getimages, if i click on it it shows me the J quarry script.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.