简体   繁体   中英

How do I update a dynamically created number with an AJAX success function?

I'm creating a voting system with a mongo backend, and I'm trying to figure out how to update the number on the front end after a vote is placed. Right now the number is being displayed dynamically with handlebars. On .up click the ajax does it's thing and sends data to the server, then returns gameData. Basically I'm wanting my {{currentvote}} number to update on success.

$('.up').on('click', function() {
    var id = this.id;

    $.ajax({
        type: "POST",
        url: "/api/upvote",
        data: JSON.stringify({ cardId: id }),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(gameData){
            console.log(gameData.currentvote + 1);

        },
        failure: function(errMsg) {
            alert(errMsg);
        }
    });
});

<div class="col-lg-12">
    <div class="row">
    <div class="up" id="{{ID}}"><i class="fas fa-chevron-circle-up color-gray upvote"></i></div>
    <div class="down" id="{{ID}}"><i class="fas fa-chevron-circle-down color-gray downvote"></i></div>
    <div class="margin-left"><p class="vote-number" id="green">{{currentvote}}</p></div>
    </div>
</div>

As you are doing it in jquery ajax you should get it done by jquery too. You can easily do it like this way:

success: function(gameData){
    var currentVote = $(".vote-number").text();
    $(".vote-number").text( parseInt(currentVote) + parseInt(gameData.currentvote) + 1 );
}

Plain old JS ought to do the job.

$('.up').on('click', function() {
var id = this.id;
var upVote = document.getElementById('green');
$.ajax({
       type: "POST",
       url: "/api/upvote",
       data: JSON.stringify({ cardId: id }),
       contentType: "application/json; charset=utf-8",
       dataType: "json",
       success: function(gameData){
            console.log(gameData.currentvote + 1);
            upVote.innerText= parseInt(upVote.innerText) + 1;


        },
        failure: function(errMsg) {
            alert(errMsg);
        }
    });
});

EDIT: Updated to take Brad's comment into account.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM