Search code examples
jquerymaterialize

how to update materialize switch element while ajax returns error?


how to update switch status? this ajax error not update the materialize switch in my code.

$(document).on('change','.setStatus',function(){    
    if($(this).prop('checked')==true){
        var activeStatus=1;     
    }else{
        var activeStatus=0;     
    }

    $.ajax({
    type:'POST',
    url:'service.php',
    data:{'status':activeStatus,'userId':userId},
    success:function(data){
    },          
    error:function(){
        if(activeStatus==1){
            $(this).prop('checked',false);      // but this not update.                         
        }else{
            $(this).prop('checked',true);   // but this not update.                     
        }
    }               
   });
});

Solution

  • $(this) doesn't work inside callbacks. So store $(this) in variable to update. Like

    $(document).on('change','.setStatus',function(){    
        var this1 = $(this);
        if(this1.prop('checked')==true){
            var activeStatus=1;     
        }else{
            var activeStatus=0;     
        }
    
        $.ajax({
        type:'POST',
        url:'service.php',
        data:{'status':activeStatus,'userId':userId},
        success:function(data){
        },          
        error:function(){
            if(activeStatus==1){
                this1.prop('checked',false);      // this will update.                         
            }else{
                this1.prop('checked',true);   // this will update.                     
            }
        }               
       });
    });
    

    Or you can use context variable.. By default, the context is an object that represents the ajax settings used in the call. So inside callback this will refer to current context. You can do like

    $(document).on('change','.setStatus',function(){    
        if($(this).prop('checked')==true){
            var activeStatus=1;     
        }else{
            var activeStatus=0;     
        }
    
        $.ajax({
        type:'POST',
        url:'service.php',
        context: $(this),
        data:{'status':activeStatus,'userId':userId},
        success:function(data){
        },          
        error:function(){
            if(activeStatus==1){
                $(this).prop('checked',false);      //  this will update.                         
            }else{
                $(this).prop('checked',true);   //  this will update.                     
            }
        }               
       });
    });
    

    You can read more about context here