douxie1692 2018-04-13 02:52
浏览 96
已采纳

通过ajax更新laravel数据库

Question

How can I update only 1 column of my table with Ajax using checkbox?

Explanation

I want to use checkbox and update my active column, the value will be either 1 or 0. If checked value is 1 otherwise 0.

Codes

html

<label class="switch">
  <input type="checkbox" data-name="active" data-id="{{ $courier->id }}">
  <span class="slider round"></span>
</label>

data-name is name of my column

data-id is my row id

controller function

public function Updatecourierstatus(Request $request) {
        try {
            $id = $request->input('id');
            $field = $request->input('name');

            $courier = Courier::findOrFail($id);
            $courier->{$field} = //must get 1 or 0 here;
            $courier->save();
        } catch (Exception $e) {
            return response($e->getMessage(), 400);
        }
        return response('', 200);
    }

route

Route::post('/Updatecourierstatus', 'CourierController@Updatecourierstatus')->name('Updatecourierstatus');
});

JavaScript

not sure how to handle this part!

UPDATE

My latest codes:

script

<script>
    $(function (){
        $.ajaxSetup({
          headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        $('label.switch input[type="checkbox"]').on('click', function (event) {
          $.post("{{route('Updatecourierstatus')}}", { 
            id: $(this).data("id"),
            name: $(this).data("name"),
            state: $(this).is(":checked") ? 0 : 1 // toggles
          }).done(function(data) {
              console.log(data)
          });
        });
    });
</script>

controller

public function Updatecourierstatus(Request $request) {
            try {
                $id = $request->input('id');
                $field = $request->input('name');
                $state = $request->input('state');

                $courier = Courier::findOrFail($id);
                $courier->{$field} = (int) $state;
                $courier->save();
            } catch (Exception $e) {
               return response($e->getMessage(), 400);
            }
            return response('', 200);
    }

html

<label class="switch">
  <input class="status" type="checkbox" data-name="active" data-id="{{ $courier->id }}" {{ $courier->active == '1' ? 'checked' : ''}}>
  <span class="slider round"></span>
</label>

Issues

  1. My switch buttons not working as expected, on for value 1 and off for value 0, the are always off.
  2. I added {{ $courier->active == '1' ? 'checked' : ''}} in order to get right on and off base on values in DB, but since then my values will not change in DB they stay on their current values and not get updated

FIXED

The issue was state: $(this).is(":checked") ? 0 : 1 as "What are the PHP operators “?” and “:” called and what do they do?" explained I had to use state: $(this).is(":checked") ? 1 : 0

  • 写回答

3条回答 默认 最新

  • douyingtai6662 2018-04-13 03:25
    关注

    I'm guessing the html which your showing is using a lib, you should check the lib for details, they might provide events which get fired which you can use.

    If not, you could do it like the following and just send up an ajax request, when you toggle the value, from looking at code name looks arbitrary set, you should perhaps not do that in case someone sends up a moody column name.

    Ok, so you could do an ajax request on click of the checkbox and get id and name from the data attributes.

    <script>
        $(function (){
            $('label.switch input[type="checkbox"]').on('click', function (event) {
              $.post("/Updatecourierstatus", { 
                id: $(this).data("id"),
                name: $(this).data("name"),
                state: $(this).is(":checked") ? 0 : 1 // toggles
              }).done(function(data) {
                  console.log(data)
              });
            });
        });
    </script>
    

    Then in your controller, just add that value:

    public function Updatecourierstatus(Request $request) {
        try {
            $id = $request->input('id');
            $field = $request->input('name');
            $state = $request->input('state');
    
            $courier = Courier::findOrFail($id);
            $courier->{$field} = (int) $state;
            $courier->save();
        } catch (Exception $e) {
           return response($e->getMessage(), 400);
        }
        return response('', 200);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀