简体   繁体   中英

Is it a good idea to use session data to reflect changes to a web page upon reloading?

Usually, AJAX is used for dynamically modifying web pages by asynchronously communicating with the backend (in my case, CodeIgniter) to avoid page reloading.

However, I am thinking about using session data to do the same for those cases where page reloading is not an issue .

Here is a code snippet of what I am trying to do:

if($this->Member_model->checkPassword($data)){ //checks whether old password is correct
    $this->Member_model->setPassword($new_pass); //sets the new password
    $this->session->set_userdata('pass_meta', 'success'); //stores success in session data
}
else {
    $this->session->set_userdata('pass_meta', 'fail'); //stores fail in session data
}
redirect('profile','refresh'); //refreshes the page

And while building the profile page, this is what I am doing:

if($this->session->userdata('pass_meta')){ //checks whether the field pass_meta is set in the session
    $data['pass_meta'] = $this->session->userdata('pass_meta'); //reads the field into $data (which will be passed to the page)
    $this->session->unset_userdata('pass_meta'); //unsets the field in the session
}
else {
    $data['pass_meta'] = "";
}

So the success/failure message gets passed to the View which triggers the appropriate message.

Now, this method is working perfectly for me. My question is: is doing this a good idea? What may be the pros/cons of this design approach?

Most frameworks implement something called flash messages, which are messages stored in session for one request only. This prevents issues with messages persisting when they should not. There is nothing wrong in using session like that, the main consideration is not to swamp session with too much data (especially if you're using server space to store sessions).

EDIT: Usually you just pass the whole message/translation key to the session storage, and then display it in your views with proper class. That way you can use generic warning/success messages in different view with no need for additional logic for each one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM