0

I have a like and dislike system in a page, like and dislike works only on the first page but not on others post. Here is what I have tried

This is how I fetch information Here is the php part

Like.php
if(isset($_POST['id'])){
$send = mysqli_query($connecDB, "UPDATE portfolio SET `like`='$view' WHERE `id`='$id'"); }

Javascript part

<script type="text/javascript">
$(".btn-success").click(function() {
var id = $('#id').val();
$.ajax({
    type : "POST",
    url : "ajax/like.php",
    data: "id=" + id,
  success: function(data) {
   $('#result').html(data);

}
}); 
});
</script>

Here is the HTML part

$sql = "SELECT * FROM post ORDER BY id DESC LIMIT 10";
$result = mysqli_query($connecDB, $sql);
while($rowsmall = mysqli_fetch_array($result)){
<button class="btn btn-success btn-stroke" id="result"><?php echo $rowsmall['like']; ?>&nbsp;<i class="fa fa-thumbs-o-up fa-lg"></i>  </button>
<input type="hidden" name="id" id="id" value="<?php echo $rowsmall['id']; ?>"> <?php } ?>

The problem I'm facing is that the javascript is again and again sending same hidden id.

unicorn2
  • 844
  • 13
  • 30
  • you have to reset hidden value on every click either like or dislike – Monty Jan 27 '16 at 06:46
  • [Little Bobby Tables](http://stackoverflow.com/q/332365/1270789) will have fun voting! Please [parameterise your SQL](http://bobby-tables.com/php.html). – Ken Y-N Jan 27 '16 at 06:50
  • @Monty how to reset hidden value? the result i receive from like.php is also shown on first post only –  Jan 27 '16 at 06:58

1 Answers1

1

In HTML id attribute must has an unique value in whole page and this line (var id = $('#id').val();) always return id of first post, use dataattributes to simply access post id, just like this

PHP

<?php $sql = "SELECT * FROM post ORDER BY id DESC LIMIT 10";
$result = mysqli_query($connecDB, $sql);
while($rowsmall = mysqli_fetch_array($result)){
   <button class="btn btn-success btn-stroke" data-id="<?php echo $rowsmall['id']; ?>" >
      <?php echo $rowsmall['like']; ?>&nbsp;<i class="fa fa-thumbs-o-up fa-lg"></i>  
   </button>
   <input type="hidden" name="id" value="<?php echo $rowsmall['id']; ?>"> 
<?php } ?>

JavaScript

<script type="text/javascript">
$(".btn-success").click(function() {
var id = $(this).data('id'); // get data-id atrribute
var element = this;
$.ajax({
    type : "POST",
    url : "ajax/like.php",
    data: "id=" + id,
  success: function(data) {
   $(element).html(data);

}
}); 
});
</script>
Farnabaz
  • 4,030
  • 1
  • 22
  • 42
  • it is sending an undefine value through id according to mozilla firebug –  Jan 27 '16 at 07:03