0

I have a JSON of images, and am trying to implement a gallery. I have a webpage that has all the thumbnails of the pictures. When someone clicks on a picture, it should be opened for viewing. (in a different webpage), and there should be next and previous buttons. Now , my problem is that the image I click on doesn't show up, and the console gives an error of Uncaught TypeError: Cannot read property 'src' of undefined. When clicked on previous or next those images show up fine, only the first one doesn't.

Here's the code I have:

if (readCookie("kookie")!=null) {
            var temp = readCookie("kookie");
            i = parseInt(temp);
            $.ajax ({
                  url: "items.json",       
                  type:"GET",
                  dataType: "json",
                  success: function(data) { 
                    items=data;
                  }
            });
           eraseCookie("kookie");
           show(i);


        }

I am using "kookie" to get the index of the picture clicked.

Here are my show, previous and next functions.

function previous() {
            if (i<0) i=items.length-1;
            else i--;
            show(i);
        }

function next() {
            if (i==items.length) i=0;
            else i++;
            show(i);
        }

function show (i) {
            $("#image-placeholder").html("<div><img src = '"+items[i].src+"'></div>");
        }
Hana Kim
  • 15
  • 1
  • 5
  • `items` is populated asynchronously. Therefore it's `undefined` when you attempt to access it by index, hence the error. You need to flow ***all*** logic dependant on the result of the AJAX call through the `success` handler function. See the duplicate I marked for more information – Rory McCrossan Feb 05 '18 at 15:29
  • @RoryMcCrossan Thank you! – Hana Kim Feb 05 '18 at 15:30

0 Answers0