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

查看全部
dongsheng9203
dongsheng9203
2018/10/20 15:29
  • laravel
  • php
  • ajax
  • 点赞
  • 收藏
  • 回答
    私信
满意答案
查看全部

2个回复