Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

NickCourage's avatar

How can I change a database value with a checkbox toggle using ajax?

I am trying to update the value of a boolean database field (is_active) in a blade template by toggling a checkbox input, in a form using Bootstrap 4 Toggle. This adds some additional elements which I can successfully reference using on('click').

I've got this working without ajax but am struggling to workout a solution with what I've got so far:

form.blade.php

<form action="{{route('user.profile.user-active')}}" method="POST" class="user-active">
    @csrf
    <input type="checkbox" name="is_active" value="1" @if(!Auth::user()->profile->is_active) checked @endif data-toggle="toggle" data-on="Yes" data-off="No">
    <input type="hidden" name="profile_id" value="{{Auth::user()->profile->id}}">
    <button type="submit">submit</button>
</form>

What form.blade.php looks like with Bootstrap 4 Toggle:

<form action="http://localhost:8000/user/profile/user-active" method="POST" class="user-active">
    <input type="hidden" name="_token" value="IjHbGDJlE3AXZZOjTstPL2x976DlhHXoK5TVeBOi">                
    <div class="toggle btn btn-light off" data-toggle="toggle" role="button" style="width: 61.5938px; height: 38px;">
        <input type="checkbox" name="is_active" value="1" checked="" data-toggle="toggle" data-on="Yes" data-off="No">
        <div class="toggle-group">
            <label for="" class="btn btn-primary toggle-on">Yes</label>
            <label for="" class="btn btn-light toggle-off">No</label>
            <span class="toggle-handle btn btn-light"></span>
        </div>
    </div>
    <input type="hidden" name="profile_id" value="1">
    <button type="" submit="">submit</button>
</form>

non ajax, working controller method - ProfileController.php

    public function changeUserActiveStatus(Request $request){

        $profile = Profile::findOrFail($request->profile_id);

        $profile->is_active = $request->is_active == 1 ? 0 : 1;

        $profile->save();

        return redirect()->back();
    }

jQuery:

<script>
        $(function (){
            $('form.user-active .toggle').on('click', function (event) {

                $.ajax({
                type: 'POST',
                url: "{{route('user.profile.user-active')}}",
               
            });

            });
        });	
</script>

I realise that the jQuery is not complete and I'm kind of at the limit of my skills in this area although I'm researching, googling my way through, looking at comparable examples that solve this problem etc but not getting very far at the moment.

0 likes
6 replies
tykus's avatar

You need to send some data in the AJAX request:

<script>
        $(function (){
            $('form.user-active .toggle').on('change', function (event) {
                $.ajax({
                type: 'POST',
                url: "{{route('user.profile.user-active')}}",
		data: {
			is_active: this.checked
		}
            });

            });
        });	
</script>

However, this is sending whenever the checkbox is changed; if you need to actually submit the form, then the event listener should be on the form submit event instead and the data to be send could simple serialize the jQuery object representing the form

NickCourage's avatar

@tykus - thanks for your reply. No the form doesn't need to be submitted - only when the checkbox is toggled. It's using submit at the moment though for the non ajax version, etc. I will give this a go

tykus's avatar

Ok, not that I didn't put the profile_id in the payload as well; it would be more appropriate to get this from the authenticated user in the controller instead (to prevent users toggling the is_active property for other users):

    public function changeUserActiveStatus(Request $request){

        $profile = auth()->user()->profile; 
	// assumes there is a `profile` relationship on the User model

        $profile->is_active = $request->is_active == 1 ? 0 : 1;

        $profile->save();

        return redirect()->back();
    }

NickCourage's avatar

@tykus I've taken care of that by passing the profile id in through $request->profile_id. Adding data: { is_active: this.checked } hasn't changed anything

NickCourage's avatar

In the end I found exactly what I was looking for with this like for like tutorial Laravel Update User Status Using Toggle Button Example I made it bespoke for what I needed and was able to add a flash style Bootstrap alert:

<script>
    $(function (){
        $('div.user-active .toggle').on('click', function (event) {

            var status = $('div.user-active .toggle input').prop('checked') == true ? 0 : 1; 
            
            $.ajax({
                type: "GET",
                dataType: "json",
                url: '{{route('user.profile.user-active')}}',
                data: {'is_active': status/*, 'user_id': user_id*/},
                success: function(data){
                    console.log(data.success);

                    var messages = $('.user-active-toggle-message');

                    var successHtml = 
                    '<div class="alert mb-0 mt-3 alert-success border rounded border-success">' + 
                        '<p class="mb-0"><i class="fas fa-check mr-2"></i>' + data.success  + '</p>' +
                    '</div>';

                    $(messages).html(successHtml).fadeIn().fadeOut(2500);

                }
            });


        });

    });
</script>
1 like
NickCourage's avatar

@tykus your answer didn't really help solve it but I'll give it to you as choosing my own is like giving myself a High 5 in public. I'm also using what you suggested for $profile = auth()->user()->profile; and this has meant I can just remove a hidden input and get rid of the form element altogether.

Please or to participate in this conversation.