johnnyblade johnnyblade - 29 days ago 10
jQuery Question

Update button using ajax and data-* attribute

I'm trying to make an update function instead of using forms, I use data-* attribute and ajax. I just want to prevent the button from firing after I update the values but I have a problem with my script after updating the button shouldn't be firing because the value of the input(number) and the data-* attribute of my button are already the same. I hope you can help me guys. Thanks in advance :)

$('body').on('click', '.btn-edituser', function(){
var button = $(this);
var upval = button.parent().prev().find('.data-avail').val();//get the value of the input(number)
var updateId = button.data('updateid');// this is the user id to be pass on to the php file
var tempAv = button.data('tempavail'); //doesn't get the new values after updating this is my PROBLEM

if(upval != tempAv){ //check if the input(number) has been changes value / doesn't have the same value with the data attribute (temporary)
button.addClass('disabled');
button.html('<i class="fa fa-refresh fa-spin"></i> Updating...');

$.ajax({
url:'./inc/update-avail.php',
type: 'POST',
data:{upval:upval, updateId:updateId},
success:function(data){
button.removeClass('disabled');
button.attr('data-tempavail', upval); //update the data attribute (temporary)
button.removeClass('btn-info').addClass('btn-success').html('<i class="fa fa-check"></i> Success');
setTimeout(function(){
button.removeClass('btn-success').addClass('btn-info').html('<i class="fa fa-pencil"></i> Edit');
}, 1000);
}
});
} });

Answer

In success: handler try to set data via $.data instead of $.attr as later one will stores the information directly on the element in attributes. So code should be like:

success:function(data){             
    button.removeClass('disabled');
    button.data('tempavail', upval); //update the data which can be seen via button.data('tempavail') again on next button click
    button.removeClass('btn-info').addClass('btn-success').html('<i class="fa fa-check"></i> Success');
    setTimeout(function(){                  
        button.removeClass('btn-success').addClass('btn-info').html('<i class="fa fa-pencil"></i> Edit');
    }, 1000);
}        
Comments