Home » Javascript » Bookmark count updates only once for Ajax button call

Bookmark count updates only once for Ajax button call

Posted by: admin August 19, 2018 Leave a comment

Questions:

I’m trying to update the button to show the number of bookmarks. My html is:

<button data-id="1" data-type="listing" data-action="bookmark" id="bookmark-button" class="like-button"><span class="like-icon"></span> Bookmark this listing</button>
<span id="bookmark-count">1 people bookmarked this listing</span>

The scripts are:

function to_bookmarks()
    {
        var current = $(this);
        var type = current.data('type');
        var pk = current.data('id');
        var action = current.data('action');
        var t = null
        var count = $('#bookmark-count');

        $.ajax({
            url : "/bookmarks/" + type + "/" + pk + "/",
            type : 'POST',
            data : { 'pk' : pk },

            success : function (json) {
                if(json.count = 1){
                    t = '1 person bookmarked this listing';
                } else {
                    t = json.count + ' people bookmarked this listing';
                }
                count.text(t);
            }
        });

        return false;
    }

$(function() {
    $('#bookmark-button').click(to_bookmarks);
});

My json response is {'result': True/False, 'count': 0/1 } depending whether I delete the bookmark or add in the server (and it’s correct).

For some reason, my browser only reacts to the 1st click of the button, but not consequent clicks (although the database updates correctly, it just doesn’t reflect in the client side).

Edit: for example, if I spam the button 100 times, only the first click will change the count from 1 to 0 or vice versa, and others will keep the same count. However, these clicks still affect the database and I can see bookmarks being created and deleted.

Answers: