如何一起实现jquery和CodeIgniter验证库?

时间:2012-06-16 05:54:04

标签: php codeigniter jquery codeigniter-2

我想创建一个注册表单,我想使用jquery和CI验证库。 我怎样才能做到这一点?提交表单后,我希望控件使用jquery转到验证库并返回响应。然后,如果一切顺利,我希望“表单已提交”消息显示在该页面上。

编辑:

这是我的代码。

查看

<?php $this->load->view('template/header'); ?>
<div id="add_form">
    <h2>Add New Category</h2>

    <?php echo form_open('abc/abc_category_controller/add_new_category'); ?>

    <?php

    $category_data = array(
        'name' => 'category_name',
        'id' => 'category_name',
        'value' => set_value('category_name'),
        'maxlength'   => '15'
    );

    $unit_data = array(
        'name' => 'unit',
        'id' => 'unit',
        'value' => set_value('unit'),
        'maxlength'   => '10'
    );

    ?>

    <p><label for="name">Name: </label><?php echo form_input($category_data); ?></p>

    <p><label for="unit">Unit: </label><?php echo form_input($unit_data); ?></p>

    <p><?php echo form_submit('submit', 'Submit','id="submit"'); ?></p>

    <?php echo form_close(); ?>

    <?php echo validation_errors('<p class="error">'); ?>

</div><!--end add new category-form-->

<div id="success_msg">


</div>



<?php $this->load->view('template/footer') ?>

Controller- add_new_category

<?php

    class Stocks_category_controller extends CI_Controller{

    function add_new_category()
    {
        //$this->load->helper('form');
        $this->load->library('form_validation');

        $data['title'] = 'Add a new category';

        $this->form_validation->set_rules('category_name', 'Category Name', 'required');
        $this->form_validation->set_rules('unit', 'Unit', 'required');

        if ($this->form_validation->run() === FALSE)
        {
              $this->load->view('abc/add_new_category');


        }

        else
        {
            $category_name = $this->input->post('category_name');

            $unit = $this->input->post('unit');

            $this->load->model('abc/abc_category_model');

            $insert_id=$this->abc_category_model->add_new_category($category_name
                                ,$unit);


            if($insert_id!=NULL)
            {
              $this->load->view('template/success',$data);
            }

            else{
                $data['error_msg']='Error Occurred';
                $this->load->view('template/template',$data);
            }

        }

    }

    function success(){
        $data['success_msg']='New Category Successfully Created';
        $this->load->view('template/success',$data);
    }
  }

最后是模特。

   function add_new_category($category_name,$unit){

      $data = array(
           'abc_category_name' => $category_name ,
           'unit' => $unit
        );

        $this->db->insert('abc_category', $data); 
        $insert_id=$this->db->insert_id();

        return $insert_id;
   }

}

我想要的是,当我提交表单时,应该进行jquery验证。如果一切顺利,则仅使用ajax显示SUccessful消息,并且不应重新加载页面。 另外,请告诉我是否可以同时使用jquery验证和CI验证库并同时维护ajax?

2 个答案:

答案 0 :(得分:4)

要实现客户端和服务器端验证,您需要使用jquery验证插件。

所以,你需要包括:

  1. jQuery javascript library

  2. jQuery validation插件

  3. 使用

    加载javascript
    <script type="text/javascript" src="<?php echo base_url();?>js/jquery-1.6.1.min.js"></script>
    <script type="text/javascript" src="<?php echo base_url();?>js/jquery.validate.js"></script>
    <script type="text/javascript" src="<?php echo base_url();?>js/jquery.validate-rules.js"></script>
    

    然后设置表单:

    $attr = array('id' => 'demo_form');
    echo form_open('demo/validation_example', $attributes);
    

    并验证您的表单,如:

    $(document).ready(function() {
      $("#demo_form").validate({
        rules: {
                name: {
                    required: true
                },
                ...
        },
        messages: {
                 name: {
                    required: "Name required",
                },
        },
        errorElement: "span",
            errorPlacement: function(error, element) {
                    error.appendTo(element.parent());
            }
    
      });
    });
    

    并且也使用服务器端验证,因为仅使用客户端验证不是一个好习惯。

    如需更多帮助,您可以找到关于

    的好教程

    如何实施jquery validation with codeigniter

    并且正在工作demo

    在哪里可以检查jquery验证,并通过禁用浏览器的javascript,您可以检查使用php完成的codeigniter服务器端验证。

答案 1 :(得分:1)

我认为你必须使用jquery ajax。

首先,您需要发布数据。将提交按钮设置为像这样触发jquery ajax。

 $.ajax({
        type: "GET",
        url: "/controller/validate",  //your controller action handler
        dataType: "json",
        data: {name:value, name: value}, //set your post data here
        cache:false,
        success: function(data){
             //handle the callback response 
             if(data.success)
                alert("Success");
             else
                alert(data.errors);
       }
 });

接下来在您的控制器操作中,使用codeigniter验证程序验证您的帖子数据。 如果验证失败,则需要使用视图中的json_encode将错误发送回js回调函数。像这样设置数据错误, 在您的视图中(您将为/ controller / validate设置的视图),执行类似这样的操作

$data['errors'] = validation_errors();
echo json_encode($data);

您将在不刷新页面的情况下将错误发回给您。 验证成功后,只需设置$data['success']并使用if语句使用echo json_encode,这样只会检索成功数据。我已经设置了ajax脚本回调。