Untitled

Den skal ændre ikon på knapperne efter like or unlike. Men uden at reloade siden. Kan den det ?
 avatar
Esbjerg82
javascript
a year ago
2.0 kB
29
Indexable
Never
Knapper i while() { }


<?php
  if($have_i_liked != $myipadress) {
?>
    <button class="like-button bg-transparent border-0" data-image-id="<?php echo $image_id; ?>" data-liked="<?php echo $have_i_liked == $myipadress ? 'true' : 'false'; ?>">
    <i class="fa-regular fa-heart fa-beat" style="color: #d4ddde;"></i></button>
<?php
  } else {
?>
    <button class="unlike-button bg-transparent border-0" data-image-id="<?php echo $image_id; ?>" data-liked="<?php echo $have_i_liked == $myipadress ? 'true' : 'false'; ?>">
    <i class="fa-solid fa-heart fa-beat" style="color: #ff0000;"></i></button>
<?php
  }
?>


JS:



<script>
$(document).ready(function() {
  $('.like-button').click(function() {
    var imageId = $(this).attr('data-image-id');
    var data = {
      image_id: imageId
    };
    $.ajax({
      type: "POST",
      url: "pages/gallery/likeImage.php",
      data: data,
      success: function(result) {
        if(result == "success"){
            console.log("Billedet blev liket!");
            // Opdater knappens klasse
            $('.like-button[data-image-id="'+imageId+'"]').addClass('unlike-button').removeClass('like-button');
        } else if(result == "already_liked"){
            alert("Du har allerede liket dette billede.");
        }
      },
      error: function(xhr, status, error) {
        console.log("Error: " + error);
      }
    });
  });
  
  $('.unlike-button').click(function() {
    var imageId = $(this).attr('data-image-id');
    var data = {
      image_id: imageId
    };
    $.ajax({
      type: "POST",
      url: "pages/gallery/unlikeImage.php",
      data: data,
      success: function(result) {
        if(result == "success"){
            console.log("Billedet blev unlikt!");
            // Opdater knappens klasse
            $('.unlike-button[data-image-id="'+imageId+'"]').addClass('like-button').removeClass('unlike-button');
        }
      },
      error: function(xhr, status, error) {
        console.log("Error: " + error);
      }
    });
  });
});


</script>