[Answer]-How to change button tag's text on ajax's success

1👍

The problem is in the use of $(this) in the success callback. It is not the button, which is what your code is expecting. So you need to alter the code capture the reference outside of the success callback.

So below is the modified code:

  • create a local variable for the button ($this)
  • use sibling() and find() to get to the correct vote element

    $('a.btn').click( function(){
    
        //This will be the button - maybe call it $button if that's clearer
        var $this = $(this);
    
        var post_id = $(this).closest('li').data('id');
        var vote = 1;
        var ajaxOpt = {
            type: 'post',
            url: '/content/vote/',
            data: {
                'vote': vote,
                'post_id': post_id,
                },
            success: function(data){
    
                //This now works! :)
                $this.siblings('button').find('.vote').text(data.vote_new); 
    
                },
            error: function(){
                console.log('error :[');
                }
        };
        $.ajax(ajaxOpt);
    
    });
    

Here’s a JSFiddle showing the concept using your scenario.

Leave a comment