Updating session without reloading page with AJAX Laravel

66 Views Asked by At

I am working on a cart system and this is a kind of blueprint I am trying to make work. So whenever the user clicks the Add button session for the specific assignment will be created and listed on the page. I neglected increase amount/decrease amount/delete/ logic for the sake of simplicity. The problem is I can not implement logic where it will store session without refreshing the page.

This is my Controller:

    public function storeAssignmentSession($id, Request $request) {
    $assignmentId = $request->input('assignment_id');
    $quantity = 1; // Default quantity is 1
    $assignment = Assignment::find($assignmentId);

    if ($assignment) {
        $taskSession = session('session_' . $id, []);

        $existingKey = null;
        foreach ($taskSession as $key => $sessionData) {
            if ($sessionData['assignment_id'] === $assignment->id) {
                $existingKey = $key;
                break;
            }
        }

        if ($existingKey !== null) {
            $taskSession[$existingKey]['quantity'] += $quantity;
        } else {
            $taskSession[] = [
                'assignment_id' => $assignment->id,
                'assignment_name' => $assignment->assignment_name,
                'assignment_status' => $assignment->assignment_status,
                'quantity' => $quantity,
            ];
        }

        session(['session_' . $id => $taskSession]);
    }

    return redirect()->back();
}

This is my Route:

Route::post('/task/{id}/store-assignment-session', [Taskmanager::class, 'storeAssignmentSession'])->name('store_assignment_session');

This is my Blade:

<script>
$(document).ready(function() {
    // Handle the "Add" button click
    $(".add-assignment").click(function(e) {
        e.preventDefault(); // Prevent the default form submission
        
        var assignmentId = $(this).data("assignment-id");
        var taskId = {{$task->id}};
        
        $.ajax({
            type: 'POST',
            url: '/task/' + taskId + '/store-assignment-session',
            data: { assignment_id: assignmentId },
            success: function(response) {
                // Load the page to refresh the content
                location.reload();

                // Log the session data in the console
                console.log(response);
            },
            error: function(error) {
                alert('Failed to add assignment to session.');
            }
        });
    });
    
    // Handle the "Subtract" button click
    $(".subtract-assignment").click(function() {
        var key = $(this).data("key");
        var taskId = {{$task->id}};
        
        $.ajax({
            type: 'POST',
            url: '/task/' + taskId + '/subtracting-assignment-session/' + key,
            success: function(response) {
                // Load the page to refresh the content
                location.reload();
            },
            error: function(error) {
                alert('Failed to subtract assignment from session.');
            }
        });
    });
    
    // Handle the "Add" button click
    $(".add-assignment").click(function() {
        var key = $(this).data("key");
        var taskId = {{$task->id}};
        
        $.ajax({
            type: 'POST',
            url: '/task/' + taskId + '/adding-assignment-session/' + key,
            success: function(response) {
                // Load the page to refresh the content
                location.reload();
            },
            error: function(error) {
                alert('Failed to add assignment to session.');
            }
        });
    });
    
    // Handle the "Delete" button click
    $(".delete-assignment").click(function() {
        var key = $(this).data("key");
        var taskId = {{$task->id}};
        
        $.ajax({
            type: 'POST',
            url: '/task/' + taskId + '/delete-assignment-session/' + key,
            success: function(response) {
                // Load the page to refresh the content
                location.reload();
            },
            error: function(error) {
                alert('Failed to delete assignment from session.');
            }
        });
    });
});

I am new to AJAX. I need to store the session and list it on the screen without reloading the page. However, whatever I do page gets updated. Can please suggest what should I do in this situation?

1

There are 1 best solutions below

0
Tran Van Hieu On
  1. like @Linesofcode commented, you must response as array, not redirect or render page

  2. Are you using authentication system from Laravel?

Because each user have a session key, so you can not access session user from normal request.

You must add csrf token in ajax reques. To Laravel can know who is logging

<meta name="csrf-token" content="{{ csrf_token() }}" />
  
In script

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

Please reconfig ajax header