Regenerate CRSF token codeigniter on submit Ajax

后端 未结 5 602
遥遥无期
遥遥无期 2021-01-07 04:46

Hi I am looking for the process of regeneration of csrf token in codeigniter when ever a form is submitted using ajax. I want the token to be regenerated without page refres

5条回答
  •  春和景丽
    2021-01-07 05:18

    I find using the form helper function works better with Codeigniter CSRF and stops throwing the CSRF error If you use normal html input will keep throwing CSRF error.

    • http://www.codeigniter.com/user_guide/helpers/form_helper.html#form_input
    • http://www.codeigniter.com/user_guide/helpers/form_helper.html#form_password

    Here is a example AJAX

     'form-login'));?>
     'username',
    'id' => 'username',
    'class' => ''
    );
    
    echo form_input($username_array);
    
    ?>
    
     'password',
    'id' => 'password',
    'class' => ''
    );
    
    echo form_password($password_array);
    
    ?>
    
     'submit',
    'id' => 'submit',
    'class' => '',
    'value' => 'Submit',
    'type' => 'submit'
    );
    
    echo form_input($submit_array);
    
    ?>
    
    
    
    
    

    Example

    public function index() {
       $data['token_name'] = $this->security->get_csrf_token_name();
       $data['token_hash'] = $this->security->get_csrf_hash();
    
       $this->load->view('login_view', $data);
    }
    
    public function example() {
        $data = array('success' => false, 'messages' => array());
    
        $this->form_validation->set_rules('username', 'username', 'required');
        $this->form_validation->set_rules('password', 'password', 'required');
    
        if ($this->form_validation->run() == false) {
    
            foreach ($_POST as $key => $value) {
                $data['messages'][$key] = form_error($key);
            }
    
        } else {
    
    
            $data['success'] = true;
        }
    
        echo json_encode($data);
    }
    

提交回复
热议问题