skip to Main Content

I am new to codeigniter & javascript, I have been working with the form submission through ajax in codeigniter. I need to use form validation on the text field & other inputs in the form. I searched the web & couldn’t find any resources or references. Currently my form submission is working fine, I just need to validate my inputs using Jquery or ajax.

Here is my Model

class test_model extends CI_Model {
    function save_data()
        {
            $name = $this->input->post('Name');
            $email = $this->input->post('Email');
            $contact = $this->input->post('Contact');
            $sex = $this->input->post('Sex');
            $country = $this->input->post('Country');   
            $data = array(
                'Name' => $name,
                'Email' => $email,
                'Contact' => $contact,
                'Sex' => $sex,
                'Country' => $country);
            $result = $this->db->insert('test2',$data);
            return $result;
        }
     }

My Controller just forwards the data to Model

class test extends CI_Controller {
    function __construct() {
        parent::__construct();
        $this->load->model('test_model');
        $this->load->helper('url');
    }
    function index() {
        $this->load->view('test_index');
    }       
    function save() { 
        $data = $this->test_model->save_data();
        echo json_encode($data);        
    }
}

Here is my View

<form>
    <div class="container" style="padding-top: 80px;">

        <div class="form-group">
            <label for="Name">First Name :</label>
            <div class="col-md-4">
                <input type="text" name="Name" id="Name" class="form-control" placeholder="Your Name..">
            </div>
        </div>

        <div class="form-group">
            <label for="Contact">Contact :</label>
            <div class="col-md-4">
                <input type="text" class="form-control" id="Contact" name="Contact" placeholder="Your Contact No..">
            </div>
        </div>

        <div class="form-group">
            <label for="Sex" class="col-md-1">Gender :</label>
            <div class="form-check form-check-inline">
                <label >
                <input type="radio" class="form-check-input" name="Sex" id="Sex" value="Male">Male  </label><span style="padding-right: 10px;"></span>

                <label>
                <input type="radio" class="form-check-input" name="Sex" id="Sex" value="Female">Female </label>
            </div>
        </div>

            <div class="form-group">
                <select class="form-control custom-select col-md-4" id="Country" name="Country">
                    <option value="">Select Country</option>
                    <option value="Europe">Europe</option>
                    <option value="United Stated of America">United States of America</option>
                    <option value="India">India</option>
                </select>
            </div>

        <div class="form-group">
            <button type="button" type="submit" id="btn_save" class="btn btn-primary" >
                <span class="spinner-border spinner-border-sm"></span>Create</button>
            <button type="button"  class="btn btn-secondary" >Close</button>
        </div>
    </div>
</form>

My JS code is below :

$('#btn_save').on('click',function() {
                    var Name = $('#Name').val();
                    var Email = $('#Email').val();
                    var Contact = $('#Contact').val();
                    var Sex = $('input[name="Sex"]:checked').val();
                    var Country = $('#Country').find(":selected").val();
                    $.ajax({
                        type : "POST",
                        url : "https://localhost/newCrud/test/save",
                        dataType : "JSON",
                        data: {"Name":Name, "Email":Email, "Contact":Contact, "Sex":Sex, "Country":Country},
                        success : function (data) {
                            if(data == 1) {
                                $('[name = "Name"]').val("");
                                $('[name = "Email"]').val("");
                                $('[name = "Contact"]').val("");
                                $('[name = "Sex"]').val("");
                                $('[name = "Country"]').val();

                                alert("Data Inserted"); }
                        }
                    });
                    return false;
                });
        });

Guys, my above code works just fine, I need your help to know how can i validate my form using ajax, as it is already passing data to the model from here. As far I’ve known that Codeigniter form_validate method can’t be used in ajax form submission. Really need your help guys. Thanks for your time & suggestions.

2

Answers


  1. Why not????

    You can use CI validation as it is a built in server side validation method and you are hitting your server through AJAX

    You need to alter your code a bit

    $.ajax({
        type : "POST",
        url : "https://localhost/newCrud/test/save",
        dataType : "JSON",
        data: {"Name":Name, "Email":Email, "Contact":Contact, "Sex":Sex, "Country":Country},
        success : function (data) {
            if(data == 1) {
                $('.form-group').removeClass('has-error');
                $('[name = "Name"]').val("");
                $('[name = "Email"]').val("");
                $('[name = "Contact"]').val("");
                $('[name = "Sex"]').val("");
                $('[name = "Country"]').val();
    
                alert("Data Inserted"); 
            }
        },
        error : function (error) {
          if(error.status == 500){
            var response = error.responseJSON.validation;
            $('.form-group').removeClass('has-error');
            $.each(response, function(index, item) {
                $('[name='+index+']').closest('.form-group').addClass('has-error');
            });
          }
        }
    
    });
    

    Update your controller as like this

    public function save() { 
      // add this if not loaded earlier
      $this->load->library('form_validation');
    
      $this->form_validation->set_rules('Name','Name', 'required');
      $this->form_validation->set_rules('Contact','Contact', 'required');
      $this->form_validation->set_rules('Email','Email Address','required|valid_email');
      if ($this->form_validation->run() == FALSE) {
          $validation = $this->form_validation->error_array();
          return $this->output
                  ->set_content_type('application/json')
                  ->set_status_header(500)
                  ->set_output( json_encode(array(
                      'validation' => $validation,
                      'message' => 'validation error !!!'
                  )) );
      } 
    
      $data = $this->test_model->save_data();
      echo json_encode($data);        
    }
    

    Here i did validation for 3 fields name, email and contact. Also i used bootstrap error class ‘has-error’ to highlight failed elements.

    Login or Signup to reply.
  2. Simply use the jQuery Validate plugin (https://jqueryvalidation.org/).

    jQuery:

    $(document).ready(function () {
    
    $('#myform').validate({ // initialize the plugin
        rules: {
            field1: {
                required: true,
                email: true
            },
            field2: {
                required: true,
                minlength: 5
            }
        }
    });
    
    });
    

    HTML:

    <form id="myform">
    <input type="text" name="field1" />
    <input type="text" name="field2" />
    <input type="submit" />
    </form>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search