Skip to content
Advertisement

Laravel – Toggle value in database with checkbox and ajax

I want to toggle a boolean value in my table with a checkbox through jquery and ajax.

So whenever a user ticks the the checkbox it should toggle the value in table.

So far i came up with this but i need help:

$(document).ready(function(){
        $("input:checkbox").change(function() { 
            var isChecked = $("input:checkbox").is(":checked") ? 1:0; 
            $.ajax({
                type:'POST',
                url:'/activation',
                headers: {'X-CSRF-TOKEN': '{{ csrf_token() }}' },
                data: $('.checkbox').serialize(),
                    success:function(data){

                    }
            });
        });
    });

Advertisement

Answer

The only thing I’d modify would be returning an answer to the ajax call to let it know what’s happening.

public function activation(Request $request)
{

    $user = User::findOrFail($request->user_id);

    if($user->active == 1){
        $user->active = 0;
    } else {
        $user->active = 1;
    }

    return response()->json([
      'data' => [
        'success' => $user->save(),
      ]
    ]);
}

And now in the front-end part:

$(document).ready(function(){
  $("input:checkbox").change(function() {
    var user_id = $(this).closest('tr').attr('id');

    $.ajax({
            type:'POST',
            url:'/activation',
            headers: {'X-CSRF-TOKEN': '{{ csrf_token() }}' },
            data: { "user_id" : user_id },
            success: function(data){
              if(data.data.success){
                //do something
              }
            }
        });
    });
});

jQuery Ajax documentation

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement