0

I'm working on a simple button that will allows to increment a line in my table. Thanks to AJAX, when the button +1 is clicked, it is replaced by a -1 button. But the problem occurs when I click once on +1, then -1 and a second time on +1.

This is what i'm having :

vote = 0
click on "+1"
 vote = 1
click on "-1"
 vote = 0
click on "+1"
 vote = 2
click on "-1"
 vote = 0
click on "+1"
 vote = 3

So as you can see, vote should be egal to 1...

Here is my code :

<?php if($data['statut'] == 1) { ?>
 <button type="button" class="button" id="<?php echo $data['ID']; ?>">-1</button><?php 
} else { ?>
 <button type="button" class="button2" id="<?php echo $data['ID']; ?>">+1</button><?php 
} ?>

AJAX :

        $('button').on("click", function test() {
        $(this).off("click");

        var ID = $(this).attr("id");

        if($(this).hasClass('button2')) {
            $.ajax({
                type: "POST",
                url: "add.php",
                data: {"ID_oeuvre": ID},
                success: function(html){
                    $("button#"+ID).removeClass("button2").addClass("button").html("-1");
                    $("button#"+ID).on("click", test);
                }
            });
        } else {
            $.ajax({
                type: "POST",
                url: "delete.php",
                data: {"ID_oeuvre": ID},
                success: function(html){
                    $("button#"+ID).removeClass("button").addClass("button2").html("+1");
                    $("button#"+ID).on("click", test);
                }
            });
            $(this).on("click", test);
        };
    });

ADD.PHP

    $requete = $bdd->prepare('UPDATE vote SET nb_vote = nb_vote + 1 WHERE ID_member = :ID_member');
    $requete->execute(array('ID_member' => $member_ID));
    $requete->closeCursor();

DELETE.PHP is the same as above, just replace nb_vote + 1 with nb_vote - 1

This problem only happens when I don't reload the page. If I reload the page after each click on the button, there is no problem. So I think that the problem is due to the fact that since there is no page reloading, nb_vote kept the old value but that doesn't explain why it goes back to 0 after that...

Thank you very much for your help.

Regards.

1 Answer 1

2

You have extra event listener binded by

$(this).on("click", test);

it's in the else clause. If you open network page in firebug, you should see duplicate requests.

Sign up to request clarification or add additional context in comments.

1 Comment

Indeed, I don't know how I could have missed it ! Thank you for your answer sir !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.