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

folab's avatar
Level 1

sending cart to server with ajax not working in my Laravel Project

my ajax request code in my .js file: ' const xhr = new XMLHttpRequest(); xhr.open('POST', '/add-to-cart', true); xhr.setRequestHeader('Content-Type', 'application/json');

// Set the X-CSRF-TOKEN header xhr.setRequestHeader('X-CSRF-TOKEN', $('meta[name="csrf-token"]').attr('content'));

// Convert the cart data to JSON and send it in the request body const jsonData = JSON.stringify(cart);

xhr.onload = function () { if (xhr.status === 200) { console.log('Cart data sent successfully'); window.location.href = '/cart'; } else { console.error('Error storing cart data'); } };

xhr.onerror = function () { console.error('An error occurred while sending the request.'); };

xhr.ontimeout = function () { console.error('The request timed out.'); };

// Send the JSON data in the request body xhr.send(jsonData); '

My Route: ' Route::post('/add-to-cart', 'App\Http\Controllers\CartController@addToCart');

my CartController: ' <?php

namespace App\Http\Controllers;

use Illuminate\Http\Request; use Illuminate\Support\Facades\Session;

class CartController extends Controller { public function addToCart(Request $request) { $jsonData = $request->getContent(); $cart = json_decode($jsonData, true);

return response()->json(['message' => 'Items added to cart']);

}

public function viewCart() { $cart = session('cart', []);

return view('cart', ['cart' => $cart]);

}

} '

My cart.blade.php: '

            <tr>
                <!-- Inside your table for displaying cart items -->
            <tr>
     
            </tr>
            </tr>
		</tbody>
    </table>
	<p id="total-price">Total Price: #0.00</p>

'

My vc.js: ' (function () { console.log("Cart:", cart); ... }) ()

0 likes
0 replies

Please or to participate in this conversation.