Joey
Joey

Reputation: 17

CodeIgniter: Able to get flash data without redirect

I have been using Code Igniter for quite a while, and I understand that "Session/flash data only works after a redirect/page reload". An interesting thing I find out on my local host is that I can manage to get flash data with out reloading/redirect the page. Can any one explain to me how is this managed to work? I was hoping that I cant get any messages. In Controller:

$this->session->set_flashdata("success", "worked");
$this->load->view('layouts/main');

In Main View:

<p class = 'bg-success'>
<?php if($this ->session->flashdata('success')): ?>

<?php echo $this ->session->flashdata('success');?>


<?php endif; ?>

</p>

After this is being executed, I can view the flash data worked. How did it work? Isn't CI flash data is only going to be appear on the next user request?(i.e. a redirect/page reload?). I just loaded a view after setting the flash data, theoretically, it should not work, and no message should appear, as this is only the first request.

Upvotes: 1

Views: 2591

Answers (2)

Aman Kumar
Aman Kumar

Reputation: 4547

If you want to display session data without redirect page then you should use $this->session->userdata() in codeigniter

Controller code

$this->session->set_userdata('msg', "Done successfully..");

To mark an existing item as “flashdata”:

$this->session->mark_as_flash('msg');

Condition in view to display msg

if(isset($this->session->userdata('msg')) echo $this->session->userdata('msg') ;

Or you may use Tempdata

CodeIgniter also supports “tempdata”, or session data with a specific expiration time. After the value expires, or the session expires or is deleted, the value is automatically removed.

Similarly to flashdata, tempdata variables are regular session vars that are marked in a specific way under the ‘__ci_vars’ key (again, don’t touch that one).

To mark an existing item as “tempdata”, simply pass its key and expiry time (in seconds!) to the mark_as_temp() method:

// 'item' will be erased after 300 seconds
$this->session->mark_as_temp('msg', 300);

Upvotes: 0

Hikmat Sijapati
Hikmat Sijapati

Reputation: 6994

CodeIgniter supports flashdata, or session data that will only be available for the next request, and is then automatically cleared.This can be very useful, especially for one-time informational, error or status messages.

For more see Codeigniter Session

Upvotes: 0

Related Questions