1

I'm trying to dynamically load pictures to a profile page like site from MySQL with PHP and then add them to an unordered list with javascript. I would like each list item to also have a like button, which upon clicking calls a javascript function, passing the image name as its parameter. I've searched and found answers on how to call a function without passing it any variables, but every time I add the image name to the function call, the console log reads "undefined".

The pictures show up fine and the imgArray[i] is a string containing the file's name (e.g. photo.jpg) But

console.log(imgArray[i]) 

in the onclick function reads undefined. I've also tried

like.setAttribute()

without any results.

function showGallery(imgArray) {
    for(var i=0; i < imgArray.length; i++){ 

        var list = document.getElementById("image-list"),
            li   = document.createElement("li"),
            img  = document.createElement("img"),
            like = document.createElement("a");

        img.src = "user_images/" + imgArray[i];
        like.className = "button-like";

        li.appendChild(img);
        li.appendChild(like);
        list.appendChild(li);

        like.href = "javascript:void(0);";
        like.onclick = function() {
            console.log(imgArray[i]);
            addLike(imgArray[i]);
        };
    }
} 

function addLike(img) {
    console.log("Liking..  " + img);
    $.ajax({
       url: 'like.php',
       type: 'POST',
       data: {
           'photo': img
       },
       success: function(likes){
           console.log(likes);
       }  
   });
}
3
  • Moved the onclick function after appending to the list, because I read you can't set the onlick property before the element is added to the DOM. Commented Dec 16, 2014 at 14:17
  • You're using jQuery for your ajax call, you should use it everywhere. Commented Dec 16, 2014 at 14:21
  • Apologies for my ignorance, but why is that so? Commented Dec 16, 2014 at 16:19

1 Answer 1

2

The problem is that by the time the click event fires, imgArray[i] doesn't exists.

try doing it like this...

like.href = "javascript:void(0);";
like.imgArray = imgArray[i];
like.onclick = function() {
        console.log(this.imgArray);
        addLike(this.imgArray);
    };

Hope that helps

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

2 Comments

I can't +1 yet but forgot to thank you as well for the quick answer, Spock! Forgot all about javascript's hasty style of not waiting on anything.
That's ok. I was on my limit of max points allowed for the day anyway ;-)

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.