This question already has an answer here:
hi i want to get the this php variable by jquery and use it for ajax this my php code and i use it in php page
function product($li)
{
$result = mysqli_query($li, "SELECT * FROM product ORDER BY id ASC") or die(mysqli_error($li));
while ($Row = mysqli_fetch_array($result)) {
echo "<div class='product'>";
echo "<img src=" . $Row['imageurl'] . " width='100' height='75'>";
echo $Row['farsiname'];
echo $Row['englishname'];
echo $Row['description'];
echo $Row['price'];
echo getid($li , $Row['id']);
echo '<button class="add_to_cart">برو تو سبد</button>';
echo '<input type="hidden" class="id" name="productid" value="' . $Row['id'] . '" />';
echo '</div>';
}
}
i want to get $row['id'] by jquery when i click button please help me!
</div>
$('.add_to_cart').on('click',function(){
alert($(this).closest('.product').find('.id').val())
})
The main approach for this case is to render Javascript code with PHP.
Below there is a pseudocode showing the approach:
<script language="Javascript">
var id = <?php echo $Row['id']; ?>;
</script>
You want to get it's value from the hidden input field, right?
If so, then you simply need to do this in jQuery.
$(".id").val();
This is finding the value of the hidden input field with the class of id.
If your id is an integer:
echo '<script> var id = ' . $Row['id'] . '; </script>';
else:
echo '<script> var id = "' . $Row['id'] . '"; </script>';
Rewrite your code by follow my steps
function product($li)
{
$result = mysqli_query($li, "SELECT * FROM product ORDER BY id ASC") or die(mysqli_error($li));
while ($Row = mysqli_fetch_array($result)) {
echo "<div class='product'>";
echo "<img src=" . $Row['imageurl'] . " width='100' height='75'>";
echo $Row['farsiname'];
echo $Row['englishname'];
echo $Row['description'];
echo $Row['price'];
echo getid($li , $Row['id']);
echo '<button class="add_to_cart" data-datac="'.$Row['id']'.">برو تو سبد</button>';
echo '</div>';
}
}
//Jquery
$('.add_to_cart').click(function() {
var d = $(this).data('datac');
alert(d);
} );