简体   繁体   English

codeigniter ajax 表单验证与提交

[英]codeigniter ajax form validation with submit

i have this ajax form validation code igniter.我有这个 ajax 表单验证代码点火器。 my view is something like this我的观点是这样的

    <?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();
    ?>

and i have this javascript我有这个 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>

i have found this code on google and just customized it.我在谷歌上找到了这个代码,只是定制了它。 but the problem is, i am not that familiar with ajax, the part where the form validation fails, work perfectly fine, but when it is succes, even though it shows alert('success');但问题是,我对 ajax 不太熟悉,表单验证失败的部分工作得很好,但是当它成功时,即使它显示alert('success'); it doesnt add the value in the database.它不会在数据库中添加值。 i need to finish this projects in a few weeks.我需要在几周内完成这个项目。 please help.请帮忙。

here is where i get the validations,这是我得到验证的地方,

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

also here is my ajax_add这也是我的 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));
}

and here is my model,这是我的模型,

public function save($data)
{
    $this->db->insert($this->table, $data);
    return $this->db->insert_id();
}
  1. You dont't need to use uppercase when accessing your controller访问控制器时不需要使用大写

just use只是使用

 url = "<?php echo site_url('provinces/ajax_add')?>";
  1. Validation the request data before inserting插入前验证请求数据

try试试

public function ajax_add()
{
   $response = array(
       'success' => false 
    ) ;

   $this->load->library('form_validation');
   // add your validation
   $this->form_validation->set_rules('PROVINCE', 'PROVINCE', 'required');

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

       $data = array(
        'PROVINCE' => $this->input->post('PROVINCE')
        );

        $insert = $this->Provinces_Model->save($data);
        if($insert){
            $response['success'] = TRUE ;
            $response['message'] = 'Record created successfully' ;
         }
         else{
           $response['message'] = 'Unable to create record' ;
         }
   }
   else
   {
       $response['message'] = 'Invalid data' ;
   }

    echo json_encode($response);
}

Then check for the 'message' index in your ajax response in the javascript code然后在 javascript 代码中检查 ajax 响应中的“消息”索引

This will give an idea of where there is problem, whether its from the这将让您了解问题出在哪里,是否来自

  1. view or查看或
  2. controller or'控制器或'
  3. Model型号

i have solved it.我已经解决了。 just did put刚刚放

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

into my controller, which makes my 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);
}

and my javascript和我的 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)
                });
            }
        }
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM