通过Ajax更新laravel数据库 [英] update laravel database by ajax

查看:43
本文介绍了通过Ajax更新laravel数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用复选框使用Ajax更新表的仅1列?

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

我想使用复选框并更新我的 active 列,该值将为 1 0 .如果检查值为 1 ,否则为 0 .

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.

html

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

数据名称是我的列的名称

data-id 是我的行ID

控制器功能

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::post('/Updatecourierstatus', 'CourierController@Updatecourierstatus')->name('Updatecourierstatus');
});

JavaScript

不确定如何处理此部分!

not sure how to handle this part!

我的最新代码:

脚本

<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>

控制器

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>

问题

  1. 我的开关按钮无法正常工作,为值 1 打开,然后为关闭对于值 0 ,总是关闭.
  2. 我添加了 {{$ courier-> active =='1'吗?'checked':''}} 以便从数据库中的值开始和结束,但是从那时起我的值不会改变数据库,它们保持当前值并且不会得到更新
  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

已修复

问题出在 state:$(this).is(:checked")?0:1 作为"什么是PHP运算符?"和:"被调用,它们做什么?"解释说我必须使用 state:$(this).is(:checked")?1:0

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

推荐答案

我猜您的影片正在使用lib的html,您应该检查lib的详细信息,它们可能会提供触发的事件,您可以使用

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.

如果没有,您可以像下面那样做,只是发送一个ajax请求,当您切换值时,通过查看代码 name 看起来是任意设置,您也许不应该这样做如果有人发送了一个喜怒无常的列名.

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.

好,因此您可以单击复选框来进行ajax请求,并从数据属性中获取 id 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);
}

这篇关于通过Ajax更新laravel数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆