Do form validation with jquery ajax in codeigniter

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

1) Get get form value and pass to form as

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

    $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!


I know your question is a year old but you can use this for the latest bootstrap with 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>