I'm struggling with Flash Data in CodeIgniter.
I basically want to:
add a category to a database redirect user back to a page show a success pop-up message "Your category has been created"
So far I can add the category successfully to the db and the user input is validated correctly, only thing is I don't know how to create the pop up success message. (I don't want to load a success view), just redirect back to where they came from and show small message in the top corner or something.
Is flash data the right way to go?
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 example: “Record 2 deleted”).
Flashdata can be retrieved using the flashdata() function which takes one argument of the item to be fetched as shown below. flashdata() function makes sure that you are getting only flash data and not any other data.
Flashdata is a functionality in the CodeIgniter framework that lets you make required data available for the next server request. It makes use of session, but unlike normal session behavior, the passed data is available only for the next server request and is automatically cleared thereafter.
In your controller:
//add to db
// load session library if not auto-loaded
$this->session->set_flashdata('msg', 'Category added');
redirect('controller/method');
In the view:
<script>
// assumes you're using jQuery
$(document).ready(function() {
$('.confirm-div').hide();
<?php if($this->session->flashdata('msg')){ ?>
$('.confirm-div').html('<?php echo $this->session->flashdata('msg'); ?>').show();
<?php } ?>
});
</script>
Your can perform different session message depends what you pass to view from your controller. Noted that I am using Bootstrap as my CSS backbone.
In view,
For success case,
<?php if ($this->session->flashdata('category_success')) { ?>
<div class="alert alert-success"> <?= $this->session->flashdata('category_success') ?> </div>
<?php } ?>
For error case,
<?php if ($this->session->flashdata('category_error')) { ?>
<div class="alert alert-danger"> <?= $this->session->flashdata('category_error') ?> </div>
<?php } ?>
In controller,
For success case,
$this->session->set_flashdata('category_success', 'Success message.');
redirect("To your view");
For error case,
$this->session->set_flashdata('category_error', 'Error message.');
redirect("To your view");
For more reference you can visit: http://www.codeigniter.com/userguide2/libraries/sessions.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With