Prevent the click event from executing twice

0

Good morning I have this jquery code

<script>
$(document).ready(function(){
    $(".like").click(function(){
        var id = this.id;

        $.ajax({
            url: "megusta.php",
            type: "POST",
            data: {id:id},
            dataType: "json",
            success:function(data){
                var likes = data["likes"];
                var text = data["text"];

                $("#likes_" + id).text(likes);
                $("#" + id).html(text);
            }
        });
    });
});
</script>

I'm doing a facebook guy, so when I click on I like it changes to I do not like it anymore but when I click again to change to like it, that's when the problem comes, the click event is executed twice

    
asked by 29.11.2017 в 17:40
source

2 answers

4

Good morning, you can use "one" instead of ".click" in the event listener as I show you below:

$( "#foo" ).one( "click", function() {
  alert( "This will be displayed only once." );
});

For the case of the code you share, it would look something like the following:

$(".like").one("click",function(){
    var id = this.id;

        $.ajax({
            url: "megusta.php",
            type: "POST",
            data: {id:id},
            dataType: "json",
            success:function(data){
                var likes = data["likes"];
                var text = data["text"];

                $("#likes_" + id).text(likes);
                $("#" + id).html(text);
            }
        });
});

I hope you find it useful, greetings.

    
answered by 29.11.2017 / 17:41
source
3

Well I did this and it has worked for me

<script>
$(document).ready(function(){
    $(".like").click(function(e){
        e.preventDefault();
        e.stopImmediatePropagation();
        var id = this.id;

        $.ajax({
            url: "megusta.php",
            type: "POST",
            data: {id:id},
            dataType: "json",
            success:function(data){
                var likes = data["likes"];
                var text = data["text"];

                $("#likes_" + id).text(likes);
                $("#" + id).html(text);
            }
        });
    });
});
</script>

If someone has another solution that they would like to share, I would appreciate it!

    
answered by 29.11.2017 в 18:28