Search code examples
phpajaxlaravellaravel-session

Can't read sessions in ajax call


i am struggling with missing sessions after ajax call. Generally when page is loaded i see in debugbar all sessions:

enter image description here

Of course I am interested in cartId. If session is present I want to use it to add product to given cart with $cartId. Here is simple ajax:

window.addEventListener('DOMContentLoaded', function () {
$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

$(".buyButton").click(function () {
    addProductToCart($(this).data('id'));
});

function addProductToCart(id_product) {
    var path = 'cart/add-product';
    $.ajax({
        type: 'post',
        url: path,
        dataType: 'JSON',
        data: {
            id_product: id_product,
        },
        success: function (data) {
            alert('added!');
        },
        error: function (ajaxContext) {
            alert(ajaxContext.responseText);
        }
    });
}

});

CartController

class CartController extends Controller
{
    public $cartId;

    public function __construct()
    {
        print_r(session::all());
        $this->cartId = $this->getCartId();
        session::put('something',123);
    }
    //REST OF CODE REMOVED 
}

I have removed other methods from controller for clarity. Nothing special was there. Basically session::all returns empty array whole time. Additionally I am adding screen from console: enter image description here

Routes:

Route::group(["namespace" => 'Controllers\FrontEnd', "middleware" => 'web'], function () {
        Route::post('/cart/add-product', 'CartController@addProductToCart');
});

Kernel.php

protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
             \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
            \App\Http\Middleware\LanguageSwitcher::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
];

Basically I can't get existing sessions on ajax but when I set new session in ajax called "something" it will exist and persist. I have read many topics about that problem and usually problem was in lack of middleware => web. I have added middleware and cleared all caches with no luck.

Have somebody any ideas how to get sessions in ajax?


Solution

  • Try to manipulate sessions in the method CartController@addProductToCart and not in the controller constructor. I have a project where I put article in session card with ajax call and it's works fine. Perhaps, it's the solution