简体   繁体   English

Laravel - 使用复选框和 ajax 切换数据库中的值

[英]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.我想通过 jquery 和 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){

                    }
            });
        });
    });

@andre 's answer is correct but @andre的答案是正确的,但是

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

this part can be done by a single line这部分可以通过一行完成

$user->active = !$user->active;

The only thing I'd modify would be returning an answer to the ajax call to let it know what's happening.我唯一要修改的就是返回 ajax 调用的答案,让它知道发生了什么。

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 jQuery Ajax 文档

function toggleActive ()
{

  $this->active!=$this->active;
  return $this;
}

in controller 在控制器中


$model->toggleActive()->save();

in model create a method在模型中创建一个方法

function toggleActive ()
{

  $this->active!=(int)$this->active;
  return $this;
}

in controller在控制器中


$model->toggleActive()->save();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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