Domanda

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.

È stato utile?

Soluzione 2

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}

Altri suggerimenti

what about using setInterval for your problem this will update your comment count every 3 seconds. if you want can you change this time its given in miliseconds

$('#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()//loads the comment after clicking button instantly
        setInterval(countComments(),3000);//and check for   update counts every 3 seconds
        $('textarea#comment').val('');
    });

your comment countComments(); get called once the function
postComment( $(this).parent().parent(), 'comment' ); return success or true on success full comment posted

also use async:false

it should be like

$('#btnComment').click(function(e) {

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

});

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top