Reputation: 47
Okay, here we go. I have an image that is clickable (ingenious, right?):
<DIV id="<?PHP echo($row[number]); ?>">
<IMG TITLE="Favorite!" src="drool_bw_nobg.png"
align="center" onclick = "favorite(<?PHP echo($row[number]); ?>)">
<b>Like</b>
</DIV>
Keep in mind, I have already done this with PHP inline (example above), and done it with
an echo()
statement, and even a printf()
statement with the \'%s\'
wildcard.
Okay, when I click the image, the Favorite(id)
javascript function is called. The VERY first command is an alert();
statement, followed by some AJAX code.
The latter works perfectly, and the php script that the AJAX references does its job very well when the image on the main page is clicked.
Then you can go onto click other images too, and the everything still works perfectly, but you click an image you have already clicked on...nothing...nada...zilch. The alert()
statement doesn't even pop up.
A real head scratcher. Hopefully someone has had this problem before, and found a clever solution.
Here is my favorite() javascript function:
function favorite(id){
alert(id);
getImage = document.getElementById(id);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById(id).innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?img="+id,true);
xmlhttp.send();
}
As I said, everything works the first time, but you have to refresh the page before you can click the same image again.
Upvotes: 1
Views: 447
Reputation: 97120
Well, here's the issue. You have this content (I've removed all irrelevant tags/attributes/PHP):
<DIV id="1">
<IMG onclick="favorite(1);"/>
</DIV>
When you click on the IMG
, the favorite()
function gets called. You then get your contents via AJAX, and update the innerHTML
of the DIV
element. At this point, you're replacing the DIV
contents with the contents you retrieve from your AJAX request.
Most likely, the AJAX contents do not contain the onclick
handler, so once you've updated the element once, your onclick
handler is gone. Subsequent clicks will no longer call your favorite()
method.
Just put the onclick
handler on your DIV
instead of your IMG
, and everything will be fine.
Upvotes: 4