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

phayes0289's avatar

Troubleshooting A javascript Ajax data submission

I am trying to use JavaScript to submit data to my controller

These are my related routes:

    Route::get('/myfireops/subscriptions', [UserSubscriptionsController::class, 'index'])->name('myfireops.subscriptions.index');
    Route::post('/myfireops/subscribe', [UserSubscriptionsController::class, 'subscribe'])->name('myfireops.subscribe.subscribe');
    Route::post('/myfireops/update-user-subscription', [UserSubscriptionsController::class, 'updateUserSubscription'])->name('myfireops.subscribe.update');
    Route::post('/myfireops/delete-user-subscription', [UserSubscriptionsController::class, 'deleteUserSubscription'])->name('myfireops.subscribe.delete');

This is an abbreviated version of the blade page that has a three-way toggle for multiple values.

<div class="container">
            <div class="row alert alert-secondary text-center">
                <div class="col-3">
                    <strong>Type</strong>
                </div>
                <div class="col-4 border-left border-secondary text-center">
                    <strong>On Duty</strong>
                </div>
                <div class="col-4 border-left border-secondary text-center">
                    <strong>Off Duty</strong>
                </div>
            </div>
            @foreach ($types as $type)
                <div class="row mb-2">
                    <!-- First Column (Expands to full width on xs screens) -->
                    <div class="col-3 ">
                        {{ $type->name }}
                    </div>
                    <!-- Second and Third Columns (Always side by side) -->
                    <div class="col-4 text-center">
                        <div class="frame-wrap mb-0">
                            <form>
                                @csrf
                                {{-- Unit Code --}}
                                <input type="hidden" name="notifier_id" id="notifier_id" value="{{ $type->id }}">
                                {{-- Type = on-duty of off-duty --}}
                                <input type="hidden" name="duty" id="duty" value="on_duty">
                                {{-- Notification Type: Incident or Vehicle --}}
                                <input type="hidden" name="notify_type" id="notify_type" value="Incident">
                                <div class="btn-group btn-group-toggle" data-toggle="buttons">
                                    <label class="btn custom-btn-color p-1 active" style="width:40px">
                                        <input type="radio" name="type" id="type" value="off" checked=checked>
                                        Off
                                    </label>
                                    <label class="btn custom-btn-color p-1" style="width:40px">
                                        <input type="radio" name="type" id="type" value="on"> On
                                    </label>
                                    <label class="btn custom-btn-color p-1" style="width:40px">
                                        <input type="radio" name="type" id="type" value="cr"> Cr
                                    </label>
                                </div>
                            </form>
                        </div>
                    </div>
                    <div class="col-4 text-center">
                        <div class="frame-wrap mb-0">
                            <form>
                                @csrf
                                {{-- User ID --}}
                                <input type="hidden" name="user_id" id="user_id" value="{{ auth()->user()->id }}">
                                {{-- Unit Code --}}
                                <input type="hidden" name="notifier_id" id="notifier_id" value="{{ $type }}">
                                {{-- Type = on-duty of off-duty --}}
                                <input type="hidden" name="duty" id="duty" value="off_duty">
                                {{-- Notification Type: Incident or Vehicle --}}
                                <input type="hidden" name="notify_type" id="notify_type" value="Incident">
                                <div class="btn-group btn-group-toggle" data-toggle="buttons">
                                    <label class="btn custom-btn-color p-1 active" style="width:40px">
                                        <input type="radio" name="type" id="type" value="off" checked=checked>
                                        Off
                                    </label>
                                    <label class="btn custom-btn-color p-1" style="width:40px">
                                        <input type="radio" name="type" id="type" value="on"> On
                                    </label>
                                    <label class="btn custom-btn-color p-1" style="width:40px">
                                        <input type="radio" name="type" id="type" value="cr"> Cr
                                    </label>
                                </div>
                            </form>
                        </div>
                    </div>

                </div>
            @endforeach
        </div>
    <script>
        $(document).ready(function() {
            $('input[type="radio"]').change(function() {
                var notifierId = $(this).closest('form').find('input[name="notifier_id"]').val();
                var type = $(this).val();

                if (type === 'on' || type === 'cr') {
                    // Send AJAX request to update the subscription
                    $.post('/myfireops/update-user-subscription', {
                        notifier_id: notifierId,
                        type: type
                    });
                } else if (type === 'off') {
                    // Send AJAX request to delete the subscription
                    $.post('/myfireops/delete-user-subscription', {
                        notifier_id: notifierId
                    }, function(data) {
                        console.log(data.message);
                    });
                }
            });
        });
    </script>

This is myUserSubscriptionsController with the updateUserSubscription method:

    public function updateUserSubscription(Request $request)
    {

        $user_id = auth()->user()->id; // Get the current user's ID
        $notifier_id = $request->input('notifier_id');
        $type = $request->input('type');
        $notify_type = $request->input('notify_type');
        $duty = $request->input('duty');

        // Find or create a record based on user_id and notifier_id
        $subscription = UserSubscription::firstOrNew([
            'user_id' => $user_id,
            'notifier_id' => $notifier_id,
        ]);

        // Update the fields
        $subscription->user_id = $user_id;
        $subscription->notifier_id = $notifier_id;
        $subscription->type = $type;
        $subscription->notify_type = $notify_type;
        $subscription->duty = $duty;

        $subscription->save();

        return response()->json(['message' => 'Subscription updated successfully']);
    }

My javascript skills are weak. I cannot see to figure out what is wrong. When I toggle a switch to "on" or "cr" , nothing is bing submitted into the database. I am not even sure I am hitting the right controller. How can I troubleshoot this code or figure out what is wrong with the code?

0 likes
2 replies
LaryAI's avatar
Level 58

It seems like you're trying to send an AJAX request to your Laravel controller but are unsure if the request is reaching the controller or if the data is being processed correctly. Here are a few steps to troubleshoot your code:

  1. Check CSRF Token: AJAX requests in Laravel require a CSRF token to be sent with the request for security reasons. Make sure you're including the CSRF token in your AJAX request.

  2. Use the correct URL: Ensure that the URL you're posting to in your AJAX request matches the route defined in your web.php.

  3. Check Network Requests: Use your browser's developer tools to check the network requests being made when you change the radio button. Look for the request to /myfireops/update-user-subscription or /myfireops/delete-user-subscription and check the response.

  4. Check Laravel Logs: If the request is being made but not processed correctly, check the Laravel logs in storage/logs/laravel.log for any errors.

  5. Add error handling to AJAX: Add error handling to your AJAX requests to log any potential errors that occur during the request.

Here's an updated version of your AJAX code with CSRF token inclusion and error handling:

$(document).ready(function() {
    $('input[type="radio"]').change(function() {
        var notifierId = $(this).closest('form').find('input[name="notifier_id"]').val();
        var type = $(this).val();
        var token = $('input[name="_token"]').val(); // Get the CSRF token

        if (type === 'on' || type === 'cr') {
            // Send AJAX request to update the subscription
            $.ajax({
                url: '/myfireops/update-user-subscription',
                type: 'POST',
                data: {
                    _token: token, // Include the CSRF token
                    notifier_id: notifierId,
                    type: type
                },
                success: function(data) {
                    console.log(data.message);
                },
                error: function(xhr, status, error) {
                    console.error("Error occurred: " + xhr.responseText);
                }
            });
        } else if (type === 'off') {
            // Send AJAX request to delete the subscription
            $.ajax({
                url: '/myfireops/delete-user-subscription',
                type: 'POST',
                data: {
                    _token: token, // Include the CSRF token
                    notifier_id: notifierId
                },
                success: function(data) {
                    console.log(data.message);
                },
                error: function(xhr, status, error) {
                    console.error("Error occurred: " + xhr.responseText);
                }
            });
        }
    });
});

Make sure to replace the url in the AJAX request with the correct URL if your application is not at the root of the domain.

By following these steps, you should be able to troubleshoot the issue and determine where the problem lies. If you find that the request is being made correctly and the controller method is being hit, but the data is still not being saved, you may need to debug your controller method to ensure that the data is being processed and saved correctly.

Please or to participate in this conversation.