NiceTry
NiceTry

Reputation: 360

Controller does not return the variable

Form can be successfully submitted via ajax and the notification message can be displayed in jquery window ("Your name has been successfully changed!")but when I submit an empty form it doesn't return the message "fail". Could you please check my code and help me to find my mistake.

Controller:

$this->load->library('form_validation');
$this->load->model('my_model');   

$this->form_validation->set_rules('name','Name','required|trim|alpha|min_length[3]|xss_clean');

if($this->form_validation->run()) {
    $user_id = $this->session->userdata('user_id');
    $name = $this->input->post('name');
    if ($this->model_users->did_change_name($user_id, $name)) {
        $data = array(
            'message_ok' => "Your name has been successfully changed!"
        );
        echo json_encode($data);
    } else { 
        $data = array(
            'message' => 'fail'                   
        );
        echo json_encode($data);         
    }
}

Upvotes: 1

Views: 72

Answers (3)

EducateYourself
EducateYourself

Reputation: 979

It's all about parentheses :) Try this way:

if($this->form_validation->run()) {
    $user_id = $this->session->userdata('user_id');
    $name = $this->input->post('name');
    if ($this->model_users->did_change_name($user_id, $name)) {
        $data = array(
            'message_ok' => "Your name has been successfully changed!"
        );
        echo json_encode($data);
    } 
}
else { 
        $data = array(
            'message' => 'fail'                   
        );
        echo json_encode($data);         
    }

Upvotes: 1

Eliel
Eliel

Reputation: 164

I haven't used CI in a good while, but from my understanding you're checking if the form was valid to run a series of events, such as a name change. But when the form validation returns false that's when one of your validation rules have failed, which it has.

if($this->form_validation->run()) {

    // your code

} else {

    $data = array(
        'message' => 'fail'                   
    );
    echo json_encode($data); 

}

Upvotes: 1

Rick Calder
Rick Calder

Reputation: 18695

if($this->form_validation->run()==TRUE) {

Right now your code is always going to return the first argument because you aren't actually checking the result of the validation. It's currently equivalent to saying if(1)

https://ellislab.com/codeigniter/user-guide/libraries/form_validation.html

Upvotes: 0

Related Questions