Laravel ajax internal servor 500 (internal server-error)

I have a shopping cart which is stored in session and I want to refresh the session without reloading the page
I have tried this:
View:

<a href="#" rel="nofollow noreferrer noopener" id="product" data-id="{{ $product->id }}" class="item_add single-item hvr-outline-out button2">Add to cart</a>

<script>
$(document).ready(function() {
    $('#product').click(function(event) {
        event.preventDefault();

        let url = "{{ route('add-to-cart') }}";
        let id = $(this).data('id');

        $.ajax({
            url: url,
            type: 'POST',
            data: {product_id: id, _token: "{{ Session::token() }}"}
        })
        .done(function() {
            console.log("success");
        })
        .fail(function() {
            console.log("error");
        })
    });
});

Route:

Route::post('/add-to-cart', '<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1747657873627463645478796365787b7b726557767373437854766563">[email protected]</a>')->name('add-to-cart');

ProductsController:
public function addToCart(Request $request)
{
    if ($request::ajax()) {
        $id = $request->product_id;

        $product = Product::find($id);

        if (Session::has('products')) {
            $products = Session::get('products');
            $products[] = $product;
            Session::put('products', $products);
        }

        else {
            $products = array($product);
            Session::put('products', $products);
        }

        return response()->json();
    }
}

And when I click add to cart it gives 500 (Internal Server Error) in the console

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You’re accessing the ajax() method statically (using ::), when you should be using -> instead:

if ($request->ajax()) {

Using the Laravel log file

As mentioned in the comments, Laravel is probably telling you this in storage/logs/laravel.log, complete with a long call-stack trace (the lines that you mentioned, beginning with “#38” and “#39”). Just scroll up to before “#1” and you’ll find your culprit.

Method 2

Laravel doesn’t allow without passing X-CSRF-TOKEN,
following is my working example hope it helps you.

Route :

Route::post('block-user','<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a2f7d1c7d0e1cdccd6d0cdcecec7d0e2e0cecdc1c9f7d1c7d0">[email protected]</a>');

Now you need to add ajax setup before your ajax call so in
blade.php :

Add this in header

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

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

//Ajax call

    $(".blockuser").bootstrapSwitch();
    $('.blockuser').on('switchChange.bootstrapSwitch', function () {
        var userid = $('#userid').val();
        $.ajax({
            url:'/block-user',
            data:{user_id : userid},
            type:'post',
            success: function(data){
                alert(data);
            }
        });
    });
</script>

Controller :
public function BlockUser(Request $request)
{
    $userid = $request->get('user_id');
//perform operation
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x