2

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

mafortis
  • 6,750
  • 23
  • 130
  • 288

3 Answers3

3

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);
}
Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106
  • thanks for answer, it is working functionally but i have 2 small issues: `1` my switch button will be active when my value become 0 which is deactivate (working opposite) `2` when I refresh my page no matter my values are 1 or 0 all my switch buttons shown as off which is 0. – mafortis Apr 13 '18 at 03:49
  • Your need to set them as checked based upon the values defined in the db, so once set with ajax upon reload set a checked attribute in the dom – Lawrence Cherone Apr 13 '18 at 03:51
  • `state ? 'checked' : ''}}>` – Lawrence Cherone Apr 13 '18 at 03:52
  • i've just tried `@if($courier->active == 1) checked @endif` it shows my buttons as expected but thee will come another issue, `even if i switch off my button it gets value of 1` because i said `@if is === 1) **checked**` so that `checked` makes it always checked. any idea? – mafortis Apr 13 '18 at 03:54
  • Im not sure I get you, use the `$(this).is(":checked")` and it should toggle fine, what lib are you using for toggling? – Lawrence Cherone Apr 13 '18 at 03:56
  • cool, update your question with your current code, as I said if you just check the checked state of the checkbox and *send up the opposite* so if its check on click you send up not checked, and then next time around the `$(this).is(":checked")` will send up is checked, see the above code it toggles beween 0 and 1 – Lawrence Cherone Apr 13 '18 at 04:03
  • Updated my question. – mafortis Apr 13 '18 at 04:09
  • well, any idea? – mafortis Apr 13 '18 at 04:18
1

You should commit a varible shows if the checkbox is checked with your ajax data param like id and name do.Then you can receive it in the controller and save it.

hellowd
  • 197
  • 1
  • 8
1

You can do this pretty easily using jquery:

$('input.checkbox').on('change', function(e) {
    $.ajax({
      type: "POST",
      url: url,
      data: {value: $(this).val(), id: $(this).data('id'), name: $(this).data('name')},
      success: function() {
        console.log('submitted')
      }
    });
});
Onfire
  • 336
  • 3
  • 13