Mike Rifgin
Mike Rifgin

Reputation: 10745

flashdata error not displaying

I'm having this strange problem with codeigniters flashdata in my login form. When I submit the form with an error in it (unrecognised email or bad email password combo) it takes two submits for the error message to display. Here's the relevant code:

//If an email address is matched
if($rowcount === 1) {
    $row = $query->row();
    if (hash('sha1', $row->salt . $_POST['password']) === $row->password) {
        //there's a matching user...create a session here and redirect to homepage  
    } else {
        $this->session->set_flashdata('credentials_error', '1');
    // echo 'recognise email but not password';
    }
} else {
    //send message back to view here
    $this->session->set_flashdata('email_error','1'); 
 }

 print_r($this->session);
 $global_data['page_data'] = $this->load->view('login-template','',true);
 $this->load->view('global', $global_data);

and the relevant bit from the view:

if($this->session->flashdata('email_error')) {
    echo '<p class="error">We dont recognise this email address.</p>';
}

if($this->session->flashdata('credentials_error')) {
    echo '<p class="error">We dont recognise these details. Please try again.</p>';
}

So if I submit the form with a bad email address that's unrecognised then I set the email_error flash data. The problem is that in the view I can see that the flashdata is set when I print out all the session data ([flash:new:emaili_error] => 1) but my error message does not show. However when I submit the form again (re-sending the same data) the error message shows.

Any ideas why this might be?

Upvotes: 1

Views: 1002

Answers (2)

Catfish
Catfish

Reputation: 19284

I always redirect instead of loading a view to get my flashdata working correctly. When you load a view, it's not submitting a new http request, but when you redirect, it is.

Upvotes: 2

Damien Pirsy
Damien Pirsy

Reputation: 25435

Yes; don't be fooled by the name they use, "sessions" in Codeigniter are cookies (they're not a fancy equivalent of the native php $_SESSION array, and they don't use it. Inf act, global arrays are usually destroyed in CI). As such, they're available only at the subsequent request; when you load the view the cookies has just been set: you need to make another request in order for the browser to catch it up and display it.

Usually flashdata are used, in fact, when you want to persist something between 2 http requests, not in the same request you set them and load a view.

It happens that you send a form, you make your checks, then you set the flashdata with the error and in the same process you load a view. The flashdata is "set" in codeigniter's class, only. When you re-submit the form, the cookie is now available, therefore you're shown the message. Hope it's clearer.

Upvotes: 3

Related Questions