codeigniter ajax表单验证与提交

时间:2016-06-12 02:20:20

标签: javascript php jquery ajax codeigniter

我有这个ajax表格验证码点火器。我的观点是这样的

    <?php

      echo form_open('Provinces/create',array('id' => 'form-user'));
    ?>

                <label for="PROVINCE" class="col-sm-2 control-label col-sm-offset-2">Province Name:</label>
                  <div class="col-sm-5">
                    <input type="text" class="form-control" id="PROVINCE" name="PROVINCE" value = "<?= set_value("PROVINCE"); ?>">
                  </div>
                <button class="btn btn-info fa fa-save" type="submit">&nbsp Save</button>
                <a href = '<?php echo base_url().'Provinces/index'; ?>' class = 'btn btn-danger fa fa-times-circle'>&nbsp Cancel</a>
     <?php

      echo form_close();
    ?>

我有这个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) {
                    // if success we would show message
                    // and also remove the error class
                    $('#the-message').append('<div class="alert alert-success">' +
                        '<span class="glyphicon glyphicon-ok"></span>' +
                        ' Data has been saved' +
                        '</div>');
                    $('.form-group').removeClass('has-error')
                                    .removeClass('has-success');
                    $('.text-danger').remove();

                    // reset the form
                    me[0].reset();

                    url = "<?php echo site_url('Provinces/ajax_add')?>";
                           // ajax adding data to database
                      $.ajax({
                        url : url,
                        type: "POST",
                        data: $('#form').serialize(),
                        dataType: "JSON",
                        success: function(data)
                        {
                           alert('success');
                        },
                        error: function (jqXHR, textStatus, errorThrown)
                        {
                            alert('Error adding / update data');
                        }
                    });

                }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>

我在谷歌上发现了这个代码并且只是定制了它。但问题是,我不熟悉ajax,表单验证失败的部分,工作完全正常,但是当它成功时,即使它显示alert('success');它也不会在数据库中添加值。我需要在几周内完成这个项目。请帮忙。

这是我获得验证的地方,

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);
}

这里也是我的ajax_add

public function ajax_add()
{
    $data = array(
            'PROVINCE' => $this->input->post('PROVINCE'),
        );
    $insert = $this->Provinces_Model->save($data);
    echo json_encode(array("status" => TRUE));
}

这是我的模特,

public function save($data)
{
    $this->db->insert($this->table, $data);
    return $this->db->insert_id();
}

2 个答案:

答案 0 :(得分:0)

  1. 访问控制器时不需要使用大写字母
  2. 只需使用

    autocomplete="off"
    
    1. 插入前验证请求数据
    2. value=""
      

      }

      然后在javascript代码

      中检查ajax响应中的'message'索引

      这将从

      中了解存在问题的位置
      1. 查看或
      2. controller或'
      3. 模型

答案 1 :(得分:0)

我已经解决了。刚刚放了

        $data = array(
                'PROVINCE' => $this->input->post('PROVINCE'),
            );
        $insert = $this->Provinces_Model->save($data);
        echo json_encode(array("status" => TRUE));

进入我的控制器,这使我的控制器

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;
        $data = array(
                'PROVINCE' => $this->input->post('PROVINCE'),
            );
        $insert = $this->Provinces_Model->save($data);
        echo json_encode(array("status" => TRUE));

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

    echo json_encode($data);
}

和我的javascript

$('#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) {
                // if success we would show message
                // and also remove the error class
                $('#the-message').append('<div class="alert alert-success">' +
                    '<span class="glyphicon glyphicon-ok"></span>' +
                    ' Data has been saved' +
                    '</div>');
                $('.form-group').removeClass('has-error')
                                .removeClass('has-success');
                $('.text-danger').remove();

                // reset the form
                me[0].reset();
                $('.alert-success').delay(500).show(10, function() {
                    $(this).delay(3000).hide(10, function() {
                        $(this).remove();
                    });
                })

            }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)
                });
            }
        }
    });
});