简体   繁体   English

如何使用Laravel和Ajax从数据库阵列中选中复选框

[英]How to get checkbox checked from database array using Laravel and Ajax

I'm trying to get data from database to checkboxes as checked. 我正在尝试将数据从数据库获取到已选中的复选框。 The checkbox data in database are as array that have been inserted with json and they are dynamic data based on insert function. 数据库中的复选框数据是使用json插入的数组,它们是基于insert函数的动态数据。

My tasks table: 我的任务表:

id |employee_id | startDate  | endDate   | ...
---|------------|------------|-----------|--------
1  |["1","2"]   | .......... | ..........| ....

My TasksController.php 我的TasksController.php

function fetchdata(Request $request)
    {
        $id = $request->input('id');
        $task = Task::find($id);
        $output = array(
            'employee_id'    =>  $task->employee_id,
            'name'    =>  $task->name,
            'description'    =>  $task->description,
            'startDate'    =>  $task->startDate,
            'endDate'    =>  $task->endDate,
            'percentage'    =>  $task->percentage       

        );
        echo json_encode($output);
    }

    public function getEmployeesList()
    {

        $employeesList = Employee::all();


        return view('adminlte::tasks', ['employeesList' => $employeesList]);


    }

My tasks.blade.php 我的tasks.blade.php

 @foreach($employeesList as $emplist)
    <label class="checkbox-inline">
      <input type="checkbox" id="employee_id" name="employee_id[]" class="chck" value="{{$emplist->id}}" >{{ $emplist->name }}</label>    
 @endforeach

My Ajax function inside blade: 我在刀片内的Ajax功能:

$(document).on('click', '.edit', function(){
        var id = $(this).attr("id");
        $('#form_output').html('');
        $.ajax({
            url: "{{route('tasks.fetchdata')}}",
            method: 'get',
            data: {id:id},
            dataType: 'json',
            success:function(data)
            {
                $('#id').val(data.id);
                $('#employee_id').val(data.employee_id);
                $('#name').val(data.name);
                .......................
                ..................
            }
        })
    });

So, how can I retrieve data from database to checkboxes as checked, because for now I'm getting null "employee_id" value when I try to update a record. 因此,如何检查已选中的数据库和复选框中的数据,因为现在在尝试更新记录时,我会得到空的“ employee_id”值。

Thank you in advance 先感谢您

Since you're encoding the data on the server side, you must decode it in the client side like : 由于您是在服务器端对数据进行编码,因此必须在客户端进行解码,例如:

...
success:function(data)
{
    console.log( data );
    data = JSON.parse(data);

    $('#id').val(data.id);
    $('#employee_id').val(data.employee_id);
    $('#name').val(data.name);
    ...

}

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

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