Framework: Session variables are not updated on ajax requests in view

Created on 28 Jun 2014  Â·  2Comments  Â·  Source: laravel/framework

Howdy,

Assume you make an ajax request.

your controller does sth like this:

controller.php:

Session::put('setup_fee',$setup_fee); //whats put in there is a string
// (.. generate html ...)
return Response::json(array('html' => $html));

and your view does sth like this:

// (...) receive data and stuff
$("#setup_fee").html(data.html + {{Session::get('setup_fee')}});

the value received is the old (initial) value of the session variable. If you reload the page (F5) the new value is there.

This does NOT happen if I pass the same session variable in a seperate variabale directly to the view on rendering, e.g. this works:

// (...) receive data and stuff
$("#setup_fee").html(data.setup_fee);

and in controller:

return Response::json(array('html' => $html,"setup_fee"=>Session::get('setup_fee')));

strange...

Most helpful comment

Since the AJAX call happens _after_ the page load, your javascript is being rendered when the session is in state A. Once you make the AJAX call, it is in state B – but by that point the call to Session::get() has already been made and the initial view has already been rendered.

So, this isn't a bug – you'll have to pass the variable through in the JSON response, like your second example.

All 2 comments

Since the AJAX call happens _after_ the page load, your javascript is being rendered when the session is in state A. Once you make the AJAX call, it is in state B – but by that point the call to Session::get() has already been made and the initial view has already been rendered.

So, this isn't a bug – you'll have to pass the variable through in the JSON response, like your second example.

Understood. Closed. And thanks for the explanation!

Was this page helpful?
0 / 5 - 0 ratings