Passing Values From PHP To JavaScript
I'm trying to get the value which is the id in the mysql database. However, each time I click on the image, I get null. I used this to get the value but it is not working as it kee
Solution 1:
You need getrating(this.id) instead. Images don't have a value property.
Solution 2:
Try this:
echo "<img src='".$row['filepath']."' id='".$row['ID']."' onclick='getrating(".$row['ID'].");'>";
Solution 3:
Or you can pass this.id
<img id="row_12" onclick="getrating(this.id)" alt="image"/>
function getrating(id){
alert(id);
}
Or you can use the event object and the currentTarget propety
<img id="row_12" onclick="getrating(event)" alt="image"/>
function getrating(e){
alert(e.currentTarget.id);
}
Solution 4:
value isn't a valid attribute of the img tag. You could use the id, or just do
echo "<img ... onclick='getrating($row[ID]);'>";
Solution 5:
An <img> doesn't have a value property.
You are doing unnecessary work in your function too. Your code should look like this:-
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
mysql_connect('localhost','root','');
mysql_select_db("ajax");
$query="SELECT * FROM xxxx";
$result= mysql_query($query);
while($row= mysql_fetch_array($result)){
echo "<img src='".$row['filepath']."' value='".$row['ID']."' id='".$row['ID']."' onclick='getrating(this);'>";
echo "<br>";
}
?>
<script type="text/javascript" >
function getrating(element){
alert(element);
}
</script>
</body>
</html>
By passing this to your function through the onclick event, you already have the element you are looking for without needing to use document.getElementById().
Post a Comment for "Passing Values From PHP To JavaScript"