它没有在使用AJAX的Codeigniter框架中显示验证错误

时间:2017-07-10 20:38:40

标签: ajax codeigniter

我在codeigniter中写了注册表。它将信息提交给数据库,但它不显示验证错误,错误消息和成功消息。但是当我写console.log(response);时,它会在控制台中显示这些消息。问题出在哪儿?

以下是我的观点:

<div id="messages"></div>
                  <?php $attributes = array('class' => 'rex-forms', 'name' => 'registrationform', 'id' => 'registrationform'); ?>
                  <?= form_open_multipart('user/register', $attributes); ?>
                      <div class="form-group">

                        <input name="username" type="text" class="form-control" placeholder="Имя пользователя">
                      </div>
                      <div class="form-group">

                        <input name="mail" type="email" class="form-control" placeholder="Электронный адрес">
                      </div>
                      <div class="form-group">

                        <input name="password" type="password" class="form-control" placeholder="Пароль">
                      </div>
                      <div class="form-group">
                        <input name="password2" type="password" class="form-control" placeholder="Повторный ввод пароля">
                      </div>                    
                  </div>
                  <div class="modal-footer">
                    <button type="submit" name="submitforreg" class="rex-bottom-medium rex-btn-icon btnsubmitforreg">
                        <span class="rex-btn-text">регистрация</span>
                        <span class="rex-btn-text-icon"><i class="fa fa-arrow-circle-o-right"></i></span>
                    </button>  
                  </div>
                  </form>

这是我的控制器:

$validator = array('success' => false, 'messages' => array());

        $validate_data = array(
            array(
                'field' => 'username',
                'label' => 'Username',
                'rules' => 'trim|required|alpha_dash|min_length[3]|max_length[30]|is_unique[instructors.instructors_slug]xss_clean'
            ),
            array(
                'field' => 'password',
                'label' => 'Password',
                'rules' => 'trim|required|md5|min_length[3]'
            ),
            array(
                'field' => 'password2',
                'label' => 'Confirm Password',
                'rules' => 'trim|required|md5|matches[password]'
            ),
            array(
                'field' => 'mail',
                'label' => 'email',
                'rules' => 'trim|required|valid_email|is_unique[instructors.mail]'
            )
        );

        $this->form_validation->set_rules($validate_data);
        $this->form_validation->set_message('is_unique', 'The {field} already exists');  
        $this->form_validation->set_error_delimiters('<p class="text-danger">', '</p>');


if ($this->form_validation->run() == FALSE)
        {
            // fails
            $validator['success'] = false;
            foreach ($_POST as $key => $value) {
                $validator['messages'][$key] = form_error($key);
            }
        } else {
    //insert the user registration details into database
            $data = array(
                'instructors_slug' => $this->input->post('username'),
                'mail' => $to_email,
                'password' => $this->input->post('password')
            );

            // insert form data into database
            if ($this->user_model->insertUser($data)) {


                if ($this->user_model->sendEmail($to_email)) {
                    // successfully sent mail
                    echo '<div class="alert alert-success text-center">You are Successfully Registered! Please confirm the mail sent to your Email-ID!!!</div>';
                }
                else
                {
                    // error
                    echo '<div class="alert alert-danger text-center">'.$to_email.'  gondermir '.$this->email->print_debugger().'</div>';
                }
            }
            else
            {
                // error
                echo '<div class="alert alert-danger text-center">daxil elemir</div>';
                    redirect('user/register');
            }
}

echo json_encode($validator);

这是我的register.js ajax文件:

$(document).ready(function() {
    $("#registrationform").unbind('submit').bind('submit', function() {
        var form = $(this);

        $.ajax({
            url: form.attr('action'),
            type: form.attr('method'),
            data: form.serialize(),
            dataType: 'json',
            success:function(response) {
            console.log(response);              
                if(response.success == true) {
                    $("#messages").html(response.messages);

                    $("#registrationform")[0].reset();
                    $(".text-danger").remove();
                    $(".form-group").removeClass('has-error').removeClass('has-success');

                }
                else {
                    $.each(response.messages, function(index, value) {
                        var element = $("#"+index);

                        $(element)
                        .closest('.form-group')
                        .removeClass('has-error')
                        .removeClass('has-success')
                        .addClass(value.length > 0 ? 'has-error' : 'has-success')
                        .find('.text-danger').remove();

                        $(element).after(value);

                    });
                }
            } // /success
        });  // /ajax

        return false;
    }); 
});

2 个答案:

答案 0 :(得分:0)

在您的代码中,您没有在每个字段中添加ID。您需要添加id,如下所述。

<?php $attributes = array('class' => 'rex-forms', 'name' => 'registrationform', 'id' => 'registrationform'); ?>
<?= form_open_multipart('user/register', $attributes); ?>
<div class="form-group">
    <input name="username" id="username" type="text" class="form-control" placeholder="Имя пользователя">
</div>
<div class="form-group">

    <input name="mail" id="mail" type="email" class="form-control" placeholder="Электронный адрес">
</div>
<div class="form-group">

    <input name="password" id="password" type="password" class="form-control" placeholder="Пароль">
</div>
<div class="form-group">
    <input name="password2"  id="password2" type="password" class="form-control" placeholder="Повторный ввод пароля">
</div>                    
</div>
<div class="modal-footer">
    <button type="submit" name="submitforreg" class="rex-bottom-medium rex-btn-icon btnsubmitforreg">
        <span class="rex-btn-text">регистрация</span>
        <span class="rex-btn-text-icon"><i class="fa fa-arrow-circle-o-right"></i></span>
    </button>  
</div>
</form>

另外在你的ajax成功功能中你可以查看下面给出的状态。

if(response.success == true){if(response.success){

如果不起作用,请告诉我。

答案 1 :(得分:0)

你应该从这个答案中得到这个想法。

用于从ajax获取验证错误。

这是发送示例电子邮件以进行验证的Ajax脚本:

$.ajax({
    type: 'POST',
    url: URL, 
    data: {
        email: email
    },
    success: function(data) {

    // Your error message 
    // Now you can show that anywhere you want inside the view.

    }

});

现在我Setting Rules Using an Array 我已使用form_validation.php

在config文件夹中添加了我的验证
email_verification' => array(
            array(
                    'field' => 'email',
                    'label' => 'Email',
                    'rules' => 'required|max_length[100]|valid_email|is_unique[your_table.email_column_name]',
                    'errors' => array(
                            'required' => 'Email  is required.',
                            'valid_email' => 'Plese Enter Valid Email',
                            'is_unique' => 'That Email is already taken. Try Again With New Email.'
                    )
            )
    )

这是控制器:

public function check_email_validation(){

    $emial = $this->input->post();

    $this->form_validation->set_error_delimiters('<span class="error">', '</div>');     

    //Now Chaeck for valid email here
    if (($this->form_validation->run('email_verification') == FALSE)){          
        // sending error message to the view. 
        echo form_error('email');
    } else {            
        unset($_POST);
        echo '<span style="color:green;" id="emailIsValid">Email Is Valid</span>';
    }

    //echo "<span style='color:green;'>Email Is Valid</span>";


}