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 使用R语言GD包一直不出结果
  • ¥15 计算机微处理器与接口技术相关问题,求解答图片的这个问题,有多少个端口,端口地址和解答问题的方法和思路,不要AI作答
  • ¥15 如何根据一个截图编写对应的HTML代码
  • ¥15 stm32标准库的PID角度环
  • ¥15 ADS已经下载好了,但是DAS下载不了,一直显示这两种情况,有什么办法吗,非常急!
  • ¥100 Excel 点击发送自动跳转outlook邮件
  • ¥15 gis中用栅格计算器或加权总和后图层不显示,值也明显不对
  • ¥15 python使用python-pptx如何给幻灯片添加只读密码。
  • ¥15 深度神经网络传递自变量损失
  • ¥15 oracle数据库备份表如何操作