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

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() }}">
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • doujun1495 2018-10-20 22:42

    Instead of: "{!!URL::to('admin/{admin}')!!}" write : `{!!url('admin/')!!}/${data[i].u_id}` and add _token and _method params to your ajax data and write like this:

      $(document).ready(function () {
      $.ajax({
        type: 'get',
        url: '{!!url('findStatus')!!}',
        success: function (data) {
          data.forEach(d => {
            console.log(d);
            if (d.status == "Active") {
              $(`#switch-${d.u_id}`).prop('checked', true);
            }
            else if (d.status == "Inactive") {
              $(`#switch-${d.u_id}`).prop('checked', false);
            }
            $(`#switch-${d.u_id}`).change(function () {
              console.log(d);
              //changed###########
              $.ajax({
                type: 'POST',
                url: `{!!url('admin/')!!}/${d.u_id}`,
                data: { _token: "{{ csrf_token() }}", _method: "PUT" },
                success: function (data) {
                  console.log(data);
                }
              });
              //###################
            });
          });
        },
        error: function (data) {
          console.log('ERROR');
        }
      });
    });
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题