Codeigniter表单验证对Ajax请求返回false

时间:2018-09-05 14:10:23

标签: php jquery ajax codeigniter

开始之前,对不起我的英语。我正在使用后端上的 CI 开发一个网站。我想建立一个注册系统而不刷新页面。如果我尝试提交表单,我没有错误,一切都很好。但是当我尝试与ajax request一起使用时,因为表单验证返回false并且validation_errorsempty,所以我无法使用表单验证。如果我禁用表单验证,则ajax请求效果很好。这是我的控制器和ajax请求。请帮助我。

User.php我的控制器

public function register(){  
$this->load->library('form_validation');
    $this->form_validation->set_rules('email_kyt', 'Email', 'is_unique[users.email]');
    $this->form_validation->set_rules('username_kyt', 'Kullanici', 'is_unique[users.username]');

   if($this->form_validation->run() == FALSE) {
        $data = json_encode(array('status'=> false,'info'=>validation_errors()));

    }else {

    if($this -> input -> is_ajax_request()){
          $userData = array(
            'email' => strip_tags($this->input->get('email_kyt')),
            //bla bla,
        );

        if ($this->User_model->form_insert($userData) == true) { //this method works perfectly.
            $data = json_encode(array('status' => true,'info' => 'Successfully Registered'));
        } else {
            $data = json_encode(array('status' => false,'info'=>'The Error Occurred During Registration'));
        }
    }else{
        $data = json_encode(array('status'=> false,'info'=>'This is not Ajax request'));
        }
    }
    echo $data;
}

}

这是我在 js

中的ajax请求
$(document).ready(function(){
  $('#btn_register').on('click',function (e) {

    $('form[name=register-form]').unbind("submit"); 
            $('form[name=register-form]').submit(function (e) {
                e.preventDefault();
                $.ajax({
                    type: 'get',
                    url: url + 'User/register', //url is correct i tested without form validation   
                    data: $('#register-form').serialize(),
                    dataType: "json",
                    success: function (data) {

                        if (data.status == true) {
                            alert(data.info);
                            window.location.reload();
                            json= [];

                        } else if (data.status == false) {
                            $('#span_validate').html(data.info);
                            json= [];
                        }

                    }
                });
            });
       });
});

编辑:这是我的表格:

<!-- Register Form -->

<?php echo form_open(base_url('index.php/User/register'),array('id' => 'register-form','name' => 'register-form')); ?>
       <?php echo  form_hidden($this->security->get_csrf_token_name(), $this->security->get_csrf_hash());  ?>
                            <div class="md-form">
                                <input type="text" id="name_kyt" name="name_kyt" class="form-control" data-toggle="popover" data-trigger="focus" data-content="...">
                                <label for="name_kyt" >Name</label>
                            </div>
                            <div class="md-form">
                                <input type="text" id="surname_kyt" name="surname_kyt" class="form-control" data-toggle="popover" data-trigger="focus" data-content="...">
                                <label for="surname_kyt" >Surname</label>
                            </div>
                            <div class="md-form">
                                <input type="text" id="username_kyt" name="username_kyt" class="form-control" data-toggle="popover" data-trigger="focus" data-content="...">
                                <label for="username_kyt" > Username </label>
                            </div>
                            <div class="md-form">
                                <input type="email" id="email_kyt" name="email_kyt" class="form-control" data-toggle="popover" data-trigger="focus" data-content="...">
                                <label for="email_kyt" >Email</label>
                            </div>
                            <div class="md-form">
                                <input type="password" id="password_kyt" name="password_kyt" class="form-control" data-toggle="popover" data-trigger="focus" data-content="...">
                                <label for="password_kyt" >Password</label>
                            </div>
                            <div class="md-form">
                                <input type="password" id="password_confirm" name="password_onay" class="form-control">
                                <label for="password_confirm" >Password Confirm</label>
                            </div>
                            <div class="form-group text-center">
                                <div class="row">
                                    <div class="col-sm-10 col-sm-offset-3 mr-auto ml-auto">
                                        <input type="submit" name="btn_register" id="btn_register" tabindex="4" class="btn btn-register mr-auto ml-auto" value="Register">
                                        <p><span id="span_validate" class="label label-default mr-auto ml-auto"></span></p>

                                    </div>
                                </div>
                            </div>
                            <!-- End of Register Form -->
                        <?php echo form_close(); ?>

2 个答案:

答案 0 :(得分:0)

Please refer below example to validate a form in CodeIgniter using ajax call.
 1. ajax code.

 $(document).ready(function(){
  $('#btn_register').on('click',function (e) {
   $('form[name=register-form]').unbind("submit"); 
        $('form[name=register-form]').submit(function (e) {
            e.preventDefault();
    var formData = $("#register-form").serialize();
            $.ajax({
                type: 'get',
                url: url + 'User/register', 
                data: formData,
                 success: function (data) {
                    if (data.status == true) {
                        alert(data.info);
                        window.location.reload();
                        json= [];
                    } else if (data.status == false) {
                        $('#span_validate').html(data.info);
                        json= [];
                    }
                }
            });
        });
    });
  });

  2. Controller code :
  Load  form_validation library and form helper
  $this->load->library('form_validation');
  $this->load->helper('form');

  Now write your controller as ...
  public function register(){  
   $this->load->library('form_validation');
   $this->load->helper('form');
   $this->form_validation->set_rules('email_kyt', 'Email', 'is_unique[users.email]');
   $this->form_validation->set_rules('username_kyt', 'Kullanici', 'is_unique[users.username]');

    if($this->form_validation->run() == FALSE) {
     echo $data = json_encode(array('status'=> false,'info'=>validation_errors())); die;

     }else {
    if($this -> input -> is_ajax_request()){
        $userData = array(
        'email' => strip_tags($this->input->get('email_kyt')),
        //bla bla,
     );

      if ($this->User_model->form_insert($userData) == true) { //this method works perfectly.
        echo $data = json_encode(array('status' => true,'info' => 'Successfully Registered')); die;
      } else {
        echo $data = json_encode(array('status' => false,'info'=>'The Error Occurred During Registration')); die;
     }
     }else{
      echo  $data = json_encode(array('status'=> false,'info'=>'This is not Ajax request')); die;
     }
   }
   }
  }

答案 1 :(得分:0)

我已经解决了这个问题。表单验证仅适用于post方法。如果使用get方法,它将无法正常工作。