Christian Burgos Christian Burgos - 1 year ago 101
jQuery Question

codeigniter session doesn't update on ajax request

why is it that codeigniter session doesn't update values when an ajax request is done?

controller index:

public function index()
$this->session->set_userdata( 'greetings', 'hello!' );

ajax request:

type: "POST",
url: "<?php echo site_url("set_greeting"); ?>",
data: data,
cache: false,
success: function(response){
alert('<?= $this->session->userdata('greetings'); ?>');


public function set_greeting()
$this->session->set_userdata( 'greetings', 'hi!' );
echo $this->session->userdata('greetings');

after the ajax request is made, I've checked firebug's console and the controller's response echoed "hi!" but the alerted value from the success of ajax is still "hello".

Answer Source

PHP is running on server side and all PHP code is rendered before sending anything to the client so alert('<?= $this->session->userdata('greetings'); ?>'); is rendered to alert('hello');.

When you do

success: function(response){ alert('<?= $this->session->userdata('greetings'); ?>'); }

it is basically saying to alert hello if the ajax request succeeds.

since PHP cannot reflect any changes done on the server side without a page refresh you cannot see changes done to server session but if you refresh the page you will be able to see the changed value because '<?= $this->session->userdata('greetings'); ?>' is renderd again on the server and now its value is changed to hi.(But in your code you won't be able to see the session change since your index method always set the value to hello. Changed value will always overwritten with the page refresh but if you use any other controller method in your system which does not set that particular session value you can reflect the change.)

Why this happens in your code ?

This happens because you're not using the response to your ajax request. You're correctly changing the server session and response is also correct but since you're not using the response you cannot see the modified value.Use the response and you should be all good.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download