javascript - codeigniter ajax 表单验证与提交

标签 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();
}

最佳答案

我已经解决了。刚刚放了

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

进入我的 Controller ,这使得我的 Controller

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

关于javascript - codeigniter ajax 表单验证与提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37770151/

相关文章:

javascript - 获取数据时将变量发送到 PHP 脚本

javascript - JQuery 验证 - 如何检测 '&' keyPress (仅允许 '&' 而不是 '7' ,因为两个键码都是 '55' )

javascript - 需要获取当前元素的id

javascript - fabric.loadSVGFromString 的扭曲结果

php - 将太平洋时间字符串转换为时间

php - 是否可以将sharedpreference中的数据插入mysql数据库?

php - 从目录加载随机图像

jquery - 在 jQuery 中预加载 wav/mp3 文件

javascript - 保存后保持选中复选框

Javascript onclick提示保存值