dongsheng9203 2018-10-20 15:29
浏览 331
已采纳

Laravel使用ajax更新数据库

Hey guys I'm using laravel 5.7 and I'm attempting to make a ajax post request to update my database. The ajax would post based on a checkbox on change function. Example if i toggle off the checkbox it would send a request and update my status to Inactive in my User table. After attempting it, i had an error of 405 (Method Not Allowed). Anyone able to note what am i doing wrong? Sorry if there are some wrong codes or syntax in my codes as I'm very new to Ajax. Any help would be appreciated.

Ajax

$(document).ready(function(){
    $.ajax({
        type:'get',
        url:'{!!URL::to('findStatus')!!}',
        success:function(data){
            for(var i=0;i<data.length;i++){

                var checkBox = document.getElementById('switch-'+data[i].u_id);

                console.log(checkBox);

                if(data[i].status == "Active"){
                    $('#switch-'+data[i].u_id).prop('checked',true);
                }

                else if(data[i].status == "Inactive")
                {
                    $('#switch-'+data[i].u_id).prop('checked',false);
                } 


                $('#switch-'+data[i].u_id).change(function(){
                    $.ajax({
                        type: "POST",
                        url : '{!!URL::to('admin/{admin}')!!}',
                        success:function(data){
                            console.log(data);
                        }
                    });
                });
            }
        },
        error:function(data){
            console.log('ERROR');
        }
    });
});

Route

Route::resource('admin','AdminController');  << I'm using the update method from the resource controller

Controller

public function update(Request $request, $id)
{
    $user = User::find($id);
    if($user->status == "Active"){
        $user->status = "Inactive";
        $user->save();
    }else{
        $user->status = "Active";
        $user->save();
    }
    return response()->json($user);
}

Form

{!!Form::open(array('action'=>['AdminController@update',$item->u_id],'method'=>'POST','id'=>'update'))!!}
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
    <input type="hidden" name="u_id" id="u_id" value="{{$item->u_id}}">
    <label class="custom-control custom-checkbox">
        <input type="checkbox" id="switch-{{$item->u_id}}" class="custom-control-input">
        <span class="custom-control-indicator"></span>
    </label>
    {{-- <button class="btn btn-primary">Update</button> --}}
{{Form::hidden('_method','PUT')}}
{!!Form::close()!!}

UPDATE

I have managed to "pass" the u_id to my post request by getting the id through target.id and splitting it with -. It is not the most elegant way but it works. But now im getting an error

POST http://manageme.test/admin/%7B2%7D 500 (Internal Server Error)

Here is what i have updated in my codes.

$('#switch-'+data[i].u_id).change(function(e){

    console.log(e.target.id);

    var s = e.target.id;
    var split = s.split('-')[1];

    $.ajax({
        type: "POST",
        url: `{!!url('admin/')!!}/{${split}}`,
        data: { _token: "{{ csrf_token() }}", _method: "PUT" },
        success:function(data){
            console.log(data);
        }
    }); 
});

these are inside my update controller

public function update(Request $request, $id)
{
    $user = User::find($id);
    if($user->status == "Active"){
        $user->status = "Inactive";
        $user->save();
    }else{
        $user->status = "Active";
        $user->save();
    }
    return response()->json($user);
}

I have also looked at the error inside the network tab of the dev tools the error message from laravel is message: "Trying to get property 'status' of non-object". I think it cant find any $user inside the update method

  • 写回答

2条回答 默认 最新

  • duanjiao2978 2018-10-21 12:13
    关注

    Solution

    I managed to fix it the problem was coming from the route trying to pass the u_id of the user and finding the user's data. So instead of typing the url inside, i made a variable to pass the route and u_id together. Here are the codes

    Ajax

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    
    
    $.ajax({
        type:'get',
        url:'{!!url('findStatus')!!}',
        success:function(data){
            for(var i=0;i<data.length;i++){
    
                var checkBox = document.getElementById('switch-'+data[i].u_id);
    
    
                if(data[i].status == "Active"){
                    $('#switch-'+data[i].u_id).prop('checked',true);
                }
    
                else if(data[i].status == "Inactive")
                {
                    $('#switch-'+data[i].u_id).prop('checked',false);
                } 
    
    
                $('#switch-'+data[i].u_id).change(function(e){
                    var s = e.target.id;
                    var split = s.split('-')[1];
                    var url = '{{route('admin.update','split')}}';
    
                    $.ajax({
                        type: 'POST',
                        url: url,
                        data: { _token: "{{ csrf_token() }}", _method: "PUT" ,u_id: split},
                        success: function(data) {
                            console.log(data['message']);
                        }
                    });
                });
            }
        },
        error:function(data){
            console.log('ERROR');
        }
    });
    

    Update method

    public function update(Request $request, $id)
    {
        $user = User::find($request['u_id']);
    
        if($user->status == "Active")
        {
            $user->status = "Inactive";
            $user->save();
            return response()->json(['message' => 'Update to Inactive']);
        }else{
            $user->status = "Active";
            $user->save();
            return response()->json(['message' => 'Update to Active']);
        }       
    }
    

    DONT forget to add the meta tag onto the document header for csrf token

     <meta name="csrf-token" content="{{ csrf_token() }}">
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置