i want to update each columns acording by id, when i click on an image, without refresh all the page. my codes just update last ids column when i click each on images.
index.php:
$rzp=mysqli_query($conn,"SELECT * FROM `tbl_users_posts` WHERE uid=1");
while($rw=mysqli_fetch_assoc($rzp)){$id=$rw['id'];
echo $id;?><img id="up" src="pc3/up.png" alt=""><br>
<?php }?>
<script>
$(document).ready(function() {
var id = <?php echo $id;?>;
$(document).on("click","#up",function() {
$.ajax({
method: "POST",
url: "y2.php",
data: {id: id},
async :false
}).done(function(msg2) {
alert(msg2);
});
});
});
</script>
y2.php:
$id=$_POST['id'];
mysqli_query($conn,"UPDATE `tbl_users_posts` SET lik=lik+1 WHERE id='$id'");
thanks
There are a couple things immediately wrong here:
id
values in your HTML, which is invalid.var id = ...
JavaScript code always has the last value from your data, and you're explicitly using that every time instead of any value from your HTML element.Let's simplify. First, echo your HTML elements to include (1) a class
to use for triggering the click handler and (2) the ID that the click handler needs:
<?php
while($rw=mysqli_fetch_assoc($rzp)){
$id=$rw['id'];
echo $id;
?>
<img class="up" src="pc3/up.png" alt="" data-id="<?php echo $id; ?>"><br>
<?php } ?>
(Note: There's probably a much cleaner way to do that. I'm attempting to maintain the coding style you currently have, but you should definitely look into cleaner approaches of writing code overall.)
Now you have a bunch of images with (1) a class
called "up" and (2) a data-
attribute with the ID you need upon clicking. Your click handler can now use that information:
$(document).on("click", ".up", function() { // use the class as the selector
var id = $(this).data('id'); // get the data-id value from this specific element
$.ajax({
method: "POST",
url: "y2.php",
data: {id: id}
}).done(function(msg2) {
alert(msg2);
});
});
(Note: I also removed async: false
because one should never use async: false
. If there's some reason you think you need to use it, that's a different problem entirely and one that should be addressed as well.)