Reuseable Like Button Jquery Script

  Kiến thức lập trình

I designed a like button which uses a script to toggle the appearance of the like button image and also record the result on my database. It works fine but the way I designed it means the script is duplicated for every like button. I am trying to figure out a way to only have the script once on my page.

HTML

The html creates the button on page load. $users5 is a variable (integer) which is different for every like button and it’s associated script. $users5 is concatenated to Show and Hide for the div ID. Clicking on the div starts the script.

<div id="hide'.$users5.'"style="display:none"><img src="unlovesm.png"></div>
<div id="show'.$users5.'"><img src="lovesm.png"></div><br>

JQuery

Depending on which “like” image is visible, the Jquery will hide that one and show the other one. And save the result with insert.php

$(document).ready(function(){
    

  $("#hide$users5").click(function(){
    
       var liked = "liked";
     var image = '$users2';
     var user = '$user2';
       $.ajax({
                    url:'insert.php',
                    method:'POST',
                    data:{
                       
                        liked:liked,
                        user:user,
                        image:image
                    },
                   success:function(data){
                         $("#hide$users5").hide();
                         $("#show$users5").show();
                       

                   }
                });
  });
  $("#show$users5").click(function(){
     
       var liked = "unliked";
        var image = '$users2';
         var user = '$user2';
       $.ajax({
                    url:'insert.php',
                    method:'POST',
                    data:{
                        
                        liked:liked,
                         user:user,
                        image:image
                    },
                   success:function(data){
                      $("#hide$users5").show();
                      $("#show$users5").hide();
 
                       
                   }
                });
  });
  

});

I think I need something like onclick=”myFunction(‘$users5’)” to send the variable to the script but some expert help is required.

I’m pretty useless at JQuery that’s why my like button ended up so weird.

New contributor

AL W is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

1

LEAVE A COMMENT