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

ondes's avatar
Level 1

LARAVEL: AJAX request dont set session variable

Hello everyone! I am trying to set up session variable by AJAX request in the Laravel. It is simple but it seems I miss something. My page has in layout cookies agreement box. After clicking to the "I agree with cookies" button within this box, AJAX request goes on- here in controller it shall set up session variable. If this session variable is set then, it shall hide always the cookies agreement box.

My ajax request on frontend:

<script>
        jQuery(document).ready(function(){
            jQuery('#accept_cookies_btn').click(function(e){
                e.preventDefault();
                $.ajaxSetup({
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                    }
                });
                jQuery.ajax({
                    url: "{{ url('/acceptcookies') }}",
                    method: 'post',
                    data: {

                    },
                    success: function(){
                        $("#cookies_con").hide();
                    }});
            });
        });
    </script>

Controller:


class cookiesController extends Controller
{
    public function acceptcookies(Request $request){
        $request->session()->put('cookies', 'agreed');
        return 'success';
    }
}


PS: Response of AJAX is good, since element #cookies_con hide after doing so. Basically the problem is it wont set up the session variable (because if I browse later, this session variable is not set- i.e. i cannot use it as a condition to hide the cookies agreement box).

PS2: All other is in order.

Thanks for any help, i believe i am missing just some detail. Carpe diem.

0 likes
17 replies
wilburpowery's avatar

Try using the Session facade instead of doing $requets->session().

Cronix's avatar

I'd use a cookie or local storage for this anyway. Otherwise, you'll annoy your users next time they login or visit as they'd have to agree again since it would be a new session.

jlrdw's avatar

Normally if no login is involved for a site, cookies aren't necessary for just viewing data.

But if a user needs to login, of course a cookie is necessary, so why an agreement. For someone totally ignorant to cookies, you could just display a message that auto hides in say 5 or 10 seconds on the new user login page. Or just have the message once on the registration page.

Snapey's avatar

If your ajax request is using the API routes then there won't be a session

2 likes
ondes's avatar
Level 1

Thanks to everyone.

Snapey: do you mean api routes within web.php? if so, why not? i miss the point...

It goes normally like this (within web.php):

Route::post('/acceptcookies','frontend\cookiesController@acceptcookies')->name('acceptcookies');

I desperately want to know whats wrong or what is missing... The ajax request works well, since it returns success and does the success function. So as I wrote above the only problem is it wont set up that session variable. This:

$request->session()->put('cookies', 'agreed');

Thanks for additional feedback!

Snapey's avatar

How do you know the session variable is not set?

ondes's avatar
Level 1

Because in f.e. blade when i use

@if(session('cookies'))....do something.....

So thats what confuses me

Snapey's avatar

You are setting the cookie in ajax. When do you generate a new view?

Laravel Debugbar is a good tool for reviewing session data

ondes's avatar
Level 1

all views have inside (by the layout) condition @if(session('cookies')=='agreed') then not display certain element. By doing that ajax request i expect set up session variable with var name cookies and val "agreed" as i described above so then if the user browses next pages on the website- the condition @if(session('cookies')=='agreed') is set so it means some elements are not displayed (those with the cookie agreement div)...

Simply, the controller statement dont put it there....:

$request->session()->put('cookies', 'agreed'); 

Everything else is working like a charm...

Thank you for your time Snapey.

Cronix's avatar
@if(session('cookies'))....do something.....

That would only get triggered if you reload the page with that code in it.

That if() check was already rendered/processed when the page initially loaded. It won't get processed again because this is an ajax request, which doesn't load that view...

ondes's avatar
Level 1

Thanks for feedback. Yeah buddy this is obvious to me, but my concern are other pages-since the

@if(session('cookies'))...do something...

...is the part of the layout which is on EACH PAGE. So it means, if part of the layout- each page child of layout has this condition. So each page with this layout when loads- runs condition if there is session var 'cookies'- if there is not, then the layout displays some element (in this case the cookies agreement box). If the session var is there- it will not get displayed.

The whole mechanism is fairly simple.

  1. you click on the button on the I AGREE in view- which sends AJAX request (and by success it does something- it does it so the AJAX request does work)

  2. in controller there shall be set session var like:

$request->session()->put('cookies', 'agreed'); 
  • and this is the place when the session var is not set up, because by browsing throught the page it shall not display certain element since:
@if(session('cookies'))...style='display:none'...

But it displays, so it means the session var was not set, so the AJAX request by its controller statement of:

$request->session()->put('cookies', 'agreed'); 

...does not set session var at all.

Any ideas?

Cronix's avatar

try using session(['key' => 'value']); instead of $request->session()->put().

ondes's avatar
Level 1

Thx,...I tried still nothing.... But Cronix, can you confirm me my approach of using AJAX is good? Since i dont understand this....

Snapey's avatar

We are assuming you have jquery, and that you have looked in the browser console and that there are no errors.

We are also assuming that your success function runs and the cookies div disappears.

Have you used the network tab in the browser to see the ajax post and response?

Please or to participate in this conversation.