Search code examples
javascriptjqueryajaxpage-refresh

Displaying the number without having to refresh


function countComments() {
    $.ajax({
        url: '/comments/' + id,
        type: 'GET',
        dataType: 'json',
        async: 'true',
        success: function(comments) {
            console.log(comments + "count");

            $('.btn-dis').html('total' + comments.length );
        }
    });
}

$('#btnComment').click(function(e) {
    e.preventDefault();
    console.log('post comment');
    // pass in the form object
    postComment( $(this).parent().parent(), 'comment' );
    // title, body, refId, commentorId, commentorName
    countComments();
    $('textarea#comment').val('');
});

Right now, I have to refresh it every time I post comment. The total should display the number of comments "automatically" or "instantly" after click button to post comment.

Any help is very much appreciated.


Solution

  • Update your comment count on postComment callback.

    Like:

    function postComment() {
        $.ajax({
            url: '/comments/add',
            type: 'POST',
            dataType: 'json',
            cache: false,
            success: function(data) {
    
              // Comment accepted.. 
              if (data.status == "ok") {
    
                console.log(data.comment_count);
              } 
            }
        });
    }
    

    and set your server to pass comment post results with json like:

    {status: "ok", comment_count: 19283}