在codeigniter中使用jquery ajax进行表单验证

时间:2022-11-24 14:22:13

How can i do form validation in codeigniter if i don't want to refresh the page? Basically i do this:

如果我不想刷新页面,我如何在codeigniter中进行表单验证?基本上我这样做:

    $config = array(
            array(
                    'field' => 'c_name',
                    'label' => 'Name',
                    'rules' => 'trim|required'
            ),
            array(
                    'field' => 'c_job',
                    'label' => 'Job',
                    'rules' => 'trim|required',
                    )
    );
    $this->form_validation->set_rules($config);
    if($this->form_validation->run() == true)
            {
                $this->load->model('model');
                //.....
            }
    else{
            $this->load->view('view');
        }

But if i send data with ajax and the page doesn't refresh, How can i do form validation?

但是,如果我使用ajax发送数据并且页面不刷新,我该如何进行表单验证?

Edit:

Thanks @ Amra Kojon. That's good and works but the new problem is this:

谢谢@Amra Kojon。这很好但有效但新问题是这样的:

if ($this->form_validation->run() == FALSE) {
                echo validation_errors();
                } 
                else {
                        //echo 'hi';


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

                        $values = array(
                                'c_name' => $value['c_name'],
                                'c_job'=> $value['c_job'],
                                'c_address'=> $value['c_address'],
                                'c_phone'=> $value['c_phone'],
                                'c_mail'=> $value['c_mail'],
                                'c_state'=> $value['c_state'],
                                'c_intrest'=> $value['c_intrest'],
                                'c_added_info'=> $value['c_added_info']
                        );


                        $add = $this->customers_model->add_customer($values);
                        echo $add;
                }  

If i just say echo "something" in the else part, It works and if the validation were OK, It echo hi but if i write theme in database (Which the value array has data and in not ajax way, it insert date), It doesn't work and the else part isn't working!!!

如果我只是说在else部分中回显“某事”,它可以工作,如果验证是正常的,它回显你好但是如果我在数据库中写主题(值数组有数据而不是ajax方式,它插入日期),它不起作用,其他部分不工作!

4 个解决方案

#1


6  

If you gave your JS- jquery Ajax code it would more efficient to understand your problem.. Don't worry! Try my following instruction...

如果您提供了JS- jquery Ajax代码,那么理解您的问题会更有效。别担心!试试我的以下指示......

1) Get get form value and pass to form as

1)获取表单值并传递给表单

<script type="text/javascript"> 
  $(document).ready(function(){
    var dataString = $("#FormId").serialize();
    var url="ControllerName/MethodName"
        $.ajax({
        type:"POST",
        url:"<?php echo base_url() ?>"+url,
        data:dataString,
        success:function (data) {
            alert(data);
        }
        });     
  })
</script>

Controller :

  1. Load library form_validation in construct as ...

    在构造中加载库form_validation为...

    $this->load->library('form_validation');

    $this->load->helper('form');

  2. Now write your controller as ...

    现在把你的控制器写成......

    function MethodName {
    $this->form_validation->set_error_delimiters('', '');
    $this->form_validation->set_rules('fname','First Name', 'required');
    $this->form_validation->set_rules('lname','Last Name', 'required');
    $this->form_validation->set_rules('email','Email Address','required|valid_email|is_unique[sec_users.email]');
    if ($this->form_validation->run() == FALSE) {
        echo validation_errors();
    } 
    else {
      // To who are you wanting with input value such to insert as 
      $data['frist_name']=$this->input->post('fname');
      $data['last_name']=$this->input->post('lname');
      $data['user_name']=$this->input->post('email');
      // Then pass $data  to Modal to insert bla bla!!
    }
    

    }

Hope will work as it is working in my application.

希望将在我的应用程序中工作。

Please accept if it is the best answer.

如果这是最佳答案,请接受。

Thank you!

#2


1  

I know your question is a year old but you can use this for the latest bootstrap with codeigniter

我知道你的问题已经有一年了,但你可以使用它来代替最新的bootignrap和codeigniter

<?php

class Yourcontroller extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->library('form_validation');
    }

    public function index() {
        $this->load->view('template/register');
    }

    public function validate() {

        $json = array();

        $this->form_validation->set_rules('username', 'Username', 'required');
        $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
        $this->form_validation->set_rules('password', 'Password', 'required|min_length[5]');
        $this->form_validation->set_rules('confirm_password', 'Confirm Password', 'required|matches[password]');
        $this->form_validation->set_rules('code', 'Login Code', 'required|numeric|min_length[4]||max_length[8]');

        $this->form_validation->set_message('required', 'You missed the input {field}!');

        if (!$this->form_validation->run()) {
            $json = array(
                'username' => form_error('username', '<p class="mt-3 text-danger">', '</p>'),
                'email' => form_error('email', '<p class="mt-3 text-danger">', '</p>'),
                'password' => form_error('password', '<p class="mt-3 text-danger">', '</p>'),
                'confirm_password' => form_error('confirm_password', '<p class="mt-3 text-danger">', '</p>'),
                'code' => form_error('code', '<p class="mt-3 text-danger">', '</p>')
            );
        }

        $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode($json));

    }
}

Ajax Script

<script type="text/javascript">
$( document ).ready(function() {
    $('#error').html(" ");

    $('#form-submit-button').on('click', function (e) {
        e.preventDefault();

        $.ajax({
            type: "POST",
            url: "<?php echo site_url('yourcontroller/validate');?>", 
            data: $("#form").serialize(),
            dataType: "json",  
            success: function(data){
                $.each(data, function(key, value) {
                    $('#input-' + key).addClass('is-invalid');

                    $('#input-' + key).parents('.form-group').find('#error').html(value);
                });
            }
        });
    });

    $('#form input').on('keyup', function () { 
        $(this).removeClass('is-invalid').addClass('is-valid');
        $(this).parents('.form-group').find('#error').html(" ");
    });
});
</script>

Full View Code

完整视图代码

<div class="container">
    <div class="row">
        <div class="col-sm-6 ml-auto mr-auto m-auto">
            <div class="card mt-5">
                <h5 class="card-header"></h5>
                <div class="card-body">
                    <?php echo form_open('agent/register', array('id' => 'form', 'role' => 'form'));?>
                    <div class="row">
                    <div class="col-sm-12">
                    <div class="form-group">
                        <?php echo form_input('username', '', array('class' => 'form-control', 'placeholder' => 'Enter Agent Username', 'id' => 'input-username'));?>
                        <div id="error"></div>
                    </div>

                    <hr/>
                    </div>
                    </div>

                    <div class="row">
                    <div class="col-sm-12">
                    <div class="form-group">
                        <?php echo form_input('email', '', array('class' => 'form-control', 'placeholder' => 'Enter Agent Email', 'id' => 'input-email'));?>
                        <div id="error"></div>
                    </div>
                    <hr/>
                    </div>
                    </div>

                    <div class="row">
                    <div class="col-sm-6">
                    <div class="form-group">
                        <?php echo form_password('password', '', array('class' => 'form-control', 'placeholder' => 'Enter Password', 'id' => 'input-password'));?>
                        <div id="error"></div>
                    </div>
                    <hr/>
                    </div>


                    <div class="col-sm-6">
                    <div class="form-group">
                        <?php echo form_password('confirm_password', '', array('class' => 'form-control', 'placeholder' => 'Enter Confirm Password', 'id' => 'input-confirm_password'));?>
                        <div id="error"></div>
                    </div>
                    <hr/>
                    </div>
                    </div>

                    <hr/>

                    <div class="row">
                    <div class="col-sm-12">
                    <div class="form-group">
                        <button type="button" class="btn btn-block btn-dark" id="form-submit-button">Register Agent</button>
                    </div>
                    </div>
                    </div>

                    <?php echo form_close();?>

                </div>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript">
$( document ).ready(function() {
    $('#error').html(" ");

    $('#form-submit-button').on('click', function (e) {
        e.preventDefault();

        $.ajax({
            type: "POST",
            url: "<?php echo site_url('yourcontroller/validate');?>", 
            data: $("#form").serialize(),
            dataType: "json",  
            success: function(data){
                $.each(data, function(key, value) {
                    $('#input-' + key).addClass('is-invalid');

                    $('#input-' + key).parents('.form-group').find('#error').html(value);
                });
            }
        });
    });

    $('#agent-register-form input').on('keyup', function () { 
        $(this).removeClass('is-invalid').addClass('is-valid');
        $(this).parents('.form-group').find('#error').html(" ");
    });
});
</script>

#3


0  

If you are aware about passing data with ajax, then the work flow is as follows.

如果您知道使用ajax传递数据,那么工作流程如下。

1) Send form data through ajax to your controller.

1)通过ajax将表单数据发送到您的控制器。

2) Do form validation as of now.

2)到目前为止进行表格验证。

3) If success then "echo" value 1

3)如果成功则“回显”值1

4) If failure, echo value 0

4)如果失败,回显值为0

So that using the value in echo, you can determine whether the validation fails or not. I can give you an example if you need

因此,使用echo中的值,您可以确定验证是否失败。如果你需要,我可以给你一个例子

Sample ajax code

样本ajax代码

$('#form').on('submit', function(e){
    e.preventDefault();
    var data = $(this).serialize();
    $.ajax({
        url: 'your url',
        type: 'POST',
        data: data,
        success: function(data){
            if(data == 1){
                $('#form')[0].reset();
                alret('success');
            }
            else if(data == 0){
                alret('failed');
            }
        },
        error: function(){
            alert('error');
        }
    });
});

#4


-3  

If using ajax,...you can't use form_validation library So you can validate on client side using jquery ...and on server side should use if statement to check submitted data

如果使用ajax,...你不能使用form_validation库所以你可以使用jquery在客户端验证...并且在服务器端应该使用if语句来检查提交的数据

#1


6  

If you gave your JS- jquery Ajax code it would more efficient to understand your problem.. Don't worry! Try my following instruction...

如果您提供了JS- jquery Ajax代码,那么理解您的问题会更有效。别担心!试试我的以下指示......

1) Get get form value and pass to form as

1)获取表单值并传递给表单

<script type="text/javascript"> 
  $(document).ready(function(){
    var dataString = $("#FormId").serialize();
    var url="ControllerName/MethodName"
        $.ajax({
        type:"POST",
        url:"<?php echo base_url() ?>"+url,
        data:dataString,
        success:function (data) {
            alert(data);
        }
        });     
  })
</script>

Controller :

  1. Load library form_validation in construct as ...

    在构造中加载库form_validation为...

    $this->load->library('form_validation');

    $this->load->helper('form');

  2. Now write your controller as ...

    现在把你的控制器写成......

    function MethodName {
    $this->form_validation->set_error_delimiters('', '');
    $this->form_validation->set_rules('fname','First Name', 'required');
    $this->form_validation->set_rules('lname','Last Name', 'required');
    $this->form_validation->set_rules('email','Email Address','required|valid_email|is_unique[sec_users.email]');
    if ($this->form_validation->run() == FALSE) {
        echo validation_errors();
    } 
    else {
      // To who are you wanting with input value such to insert as 
      $data['frist_name']=$this->input->post('fname');
      $data['last_name']=$this->input->post('lname');
      $data['user_name']=$this->input->post('email');
      // Then pass $data  to Modal to insert bla bla!!
    }
    

    }

Hope will work as it is working in my application.

希望将在我的应用程序中工作。

Please accept if it is the best answer.

如果这是最佳答案,请接受。

Thank you!

#2


1  

I know your question is a year old but you can use this for the latest bootstrap with codeigniter

我知道你的问题已经有一年了,但你可以使用它来代替最新的bootignrap和codeigniter

<?php

class Yourcontroller extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->library('form_validation');
    }

    public function index() {
        $this->load->view('template/register');
    }

    public function validate() {

        $json = array();

        $this->form_validation->set_rules('username', 'Username', 'required');
        $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
        $this->form_validation->set_rules('password', 'Password', 'required|min_length[5]');
        $this->form_validation->set_rules('confirm_password', 'Confirm Password', 'required|matches[password]');
        $this->form_validation->set_rules('code', 'Login Code', 'required|numeric|min_length[4]||max_length[8]');

        $this->form_validation->set_message('required', 'You missed the input {field}!');

        if (!$this->form_validation->run()) {
            $json = array(
                'username' => form_error('username', '<p class="mt-3 text-danger">', '</p>'),
                'email' => form_error('email', '<p class="mt-3 text-danger">', '</p>'),
                'password' => form_error('password', '<p class="mt-3 text-danger">', '</p>'),
                'confirm_password' => form_error('confirm_password', '<p class="mt-3 text-danger">', '</p>'),
                'code' => form_error('code', '<p class="mt-3 text-danger">', '</p>')
            );
        }

        $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode($json));

    }
}

Ajax Script

<script type="text/javascript">
$( document ).ready(function() {
    $('#error').html(" ");

    $('#form-submit-button').on('click', function (e) {
        e.preventDefault();

        $.ajax({
            type: "POST",
            url: "<?php echo site_url('yourcontroller/validate');?>", 
            data: $("#form").serialize(),
            dataType: "json",  
            success: function(data){
                $.each(data, function(key, value) {
                    $('#input-' + key).addClass('is-invalid');

                    $('#input-' + key).parents('.form-group').find('#error').html(value);
                });
            }
        });
    });

    $('#form input').on('keyup', function () { 
        $(this).removeClass('is-invalid').addClass('is-valid');
        $(this).parents('.form-group').find('#error').html(" ");
    });
});
</script>

Full View Code

完整视图代码

<div class="container">
    <div class="row">
        <div class="col-sm-6 ml-auto mr-auto m-auto">
            <div class="card mt-5">
                <h5 class="card-header"></h5>
                <div class="card-body">
                    <?php echo form_open('agent/register', array('id' => 'form', 'role' => 'form'));?>
                    <div class="row">
                    <div class="col-sm-12">
                    <div class="form-group">
                        <?php echo form_input('username', '', array('class' => 'form-control', 'placeholder' => 'Enter Agent Username', 'id' => 'input-username'));?>
                        <div id="error"></div>
                    </div>

                    <hr/>
                    </div>
                    </div>

                    <div class="row">
                    <div class="col-sm-12">
                    <div class="form-group">
                        <?php echo form_input('email', '', array('class' => 'form-control', 'placeholder' => 'Enter Agent Email', 'id' => 'input-email'));?>
                        <div id="error"></div>
                    </div>
                    <hr/>
                    </div>
                    </div>

                    <div class="row">
                    <div class="col-sm-6">
                    <div class="form-group">
                        <?php echo form_password('password', '', array('class' => 'form-control', 'placeholder' => 'Enter Password', 'id' => 'input-password'));?>
                        <div id="error"></div>
                    </div>
                    <hr/>
                    </div>


                    <div class="col-sm-6">
                    <div class="form-group">
                        <?php echo form_password('confirm_password', '', array('class' => 'form-control', 'placeholder' => 'Enter Confirm Password', 'id' => 'input-confirm_password'));?>
                        <div id="error"></div>
                    </div>
                    <hr/>
                    </div>
                    </div>

                    <hr/>

                    <div class="row">
                    <div class="col-sm-12">
                    <div class="form-group">
                        <button type="button" class="btn btn-block btn-dark" id="form-submit-button">Register Agent</button>
                    </div>
                    </div>
                    </div>

                    <?php echo form_close();?>

                </div>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript">
$( document ).ready(function() {
    $('#error').html(" ");

    $('#form-submit-button').on('click', function (e) {
        e.preventDefault();

        $.ajax({
            type: "POST",
            url: "<?php echo site_url('yourcontroller/validate');?>", 
            data: $("#form").serialize(),
            dataType: "json",  
            success: function(data){
                $.each(data, function(key, value) {
                    $('#input-' + key).addClass('is-invalid');

                    $('#input-' + key).parents('.form-group').find('#error').html(value);
                });
            }
        });
    });

    $('#agent-register-form input').on('keyup', function () { 
        $(this).removeClass('is-invalid').addClass('is-valid');
        $(this).parents('.form-group').find('#error').html(" ");
    });
});
</script>

#3


0  

If you are aware about passing data with ajax, then the work flow is as follows.

如果您知道使用ajax传递数据,那么工作流程如下。

1) Send form data through ajax to your controller.

1)通过ajax将表单数据发送到您的控制器。

2) Do form validation as of now.

2)到目前为止进行表格验证。

3) If success then "echo" value 1

3)如果成功则“回显”值1

4) If failure, echo value 0

4)如果失败,回显值为0

So that using the value in echo, you can determine whether the validation fails or not. I can give you an example if you need

因此,使用echo中的值,您可以确定验证是否失败。如果你需要,我可以给你一个例子

Sample ajax code

样本ajax代码

$('#form').on('submit', function(e){
    e.preventDefault();
    var data = $(this).serialize();
    $.ajax({
        url: 'your url',
        type: 'POST',
        data: data,
        success: function(data){
            if(data == 1){
                $('#form')[0].reset();
                alret('success');
            }
            else if(data == 0){
                alret('failed');
            }
        },
        error: function(){
            alert('error');
        }
    });
});

#4


-3  

If using ajax,...you can't use form_validation library So you can validate on client side using jquery ...and on server side should use if statement to check submitted data

如果使用ajax,...你不能使用form_validation库所以你可以使用jquery在客户端验证...并且在服务器端应该使用if语句来检查提交的数据