I was wondering what is wrong with this tag I am using which uses a PHP variable within an onClick event.
after looking around for other answers on this i have tried to do it but for some reason it doesnt work.
<a onclick="setCartDisplay('<?=$prodID;?>'); return false;" href="prodtest2.php?action=add&id=<?=$id;?>">
Here is the code leading up to and including the link tag that doesnt work.
$prod_query = 'SELECT * FROM *****.*****';
$prod_details = db_query_into_array_enhanced($mysql_connection, $prod_query);
$count = count($prod_details);
for($i = 0; $i < $count; $i++)
{?>
<? $prodID = $prod_details[$i]['catID'];
$prodDesc = $prod_details[$i]['shortDescription'];
$prodPrice = $prod_details[$i]['rrp'];
?>
<tr>
<td><?=$prodID;?></td>
<td><?=$prodDesc;?></td>
<td><?=$prodPrice;?></td>
<td><a onclick="setCartDisplay('<?=$prodID;?>'); return false;" href="prodtest2.php?action=add&id=<?=$prodID;?>">Add To Cart</a></td>
A better solution is to store the id
from php, as the id of the anchor element and retrieve it after using javascript.
As of html 5 any characters are valid for an id (and as it is a product ID I am guessing there will not be duplicates, if there are simply add it as a class instead with a prefix). This way would also require you to have a class on the anchors.
This gets around you having to set the onclick of the a
tag, which in my eyes is always a bad idea as it mixes your html with javascript, and imagine if you had a 1000 of these links on your page and the function name changed, you can start to see why it becomes a better solution;
The html;
<a id="<?= $prodID; ?>" class="product" href="prodtest2.php?action=add&id=<?= $id; ?>">
And the javascript (Jquery)
$(".product").click(function() {
var id = $(this).attr("id");
setCartDisplay(id);
});
The reason your link is not working in the first place is because you are returning false from your function call which disables the default behaviour of the click event.