Codeigniter ajax表单验证错误

时间:2016-06-11 11:45:11

标签: javascript php jquery ajax codeigniter

我已经研究过这个代码,它将使用ajax进行验证。

我的控制器是:

public function create(){


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

    $this->form_validation->set_rules('PROVINCE','Province Name','trim|required|max_length[30]|callback_if_exist');
    $this->form_validation->set_error_delimiters('<p class="text-danger"','</p>');

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

        $data['success'] = true;
    }else{
        foreach ($_POST as $key => $value) {
            # code...
            $data['messages']['key'] = form_error($key);
        }
    }

    echo json_encode($data);
}

我的javascript是:

<script>
    $('#form-user').submit(function(e){
        e.preventDefault();

        var me = $(this);

        // perform ajax
        $.ajax({
            url: me.attr('action'),
            type: 'post',
            data: me.serialize(),
            dataType: 'json',
            success: function(response){
                if (response.success == true){
                    alert('success');
                }else{
                    $.each(response.messages, function(key, value) {
                        var element = $('#' + key);

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

                        element.after(value)

                    });
                }
            }

        });


    });


</script>

起初我的if else声明是:

            if (response.success == true){
                alert('success');
            }else{
               alert('failed');

                });

但是当我把代码放入时:

  $.each(response.messages, function(key, value) {
                        var element = $('#' + key);

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

                    element.after(value)

如果验证失败,该按钮将不再起作用。

1 个答案:

答案 0 :(得分:1)

你正在PHP循环中对字符串'key'进行硬编码,你真正想要变量$key

更改

$data['messages']['key']

$data['messages'][$key]