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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里