Categories: Snippets

Codeigniter Ajax Form Validation Example

  1. Create Controller
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Item extends CI_Controller {

   /**
    * Get All Data from this method.
    *
    * @return Response
   */   public function __construct() {
      parent::__construct(); 

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

   /**
    * Create from display on this method.
    *
    * @return Response
   */   public function index()
   {
      $this->load->view('item');
   }

   /**
    * Store Data from this method.
    *
    * @return Response
   */   public function itemForm()
   {
        $this->form_validation->set_rules('first_name', 'First Name', 'required');
        $this->form_validation->set_rules('last_name', 'Last Name', 'required');
        $this->form_validation->set_rules('email', 'Email', 'required|valid_email');
        $this->form_validation->set_rules('address', 'Address', 'required');

        if ($this->form_validation->run() == FALSE){
            $errors = validation_errors();
            echo json_encode(['error'=>$errors]);
        }else{
           echo json_encode(['success'=>'Record added successfully.']);
        }
    }
}

2. Create View File

<!DOCTYPE html>
<html>
<head>
 <title>Codeigniter Ajax Validation Example</title>
 <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
</head>
<body>

<div class="container">
 <h2>Codeigniter Ajax Validation</h2>

 <div class="alert alert-danger print-error-msg" style="display:none">
    </div>

 <form>
  <div class="form-group">
   <label>First Name:</label>
   <input type="text" name="first_name" class="form-control" placeholder="First Name">
  </div>

  <div class="form-group">
   <label>Last Name:</label>
   <input type="text" name="last_name" class="form-control" placeholder="Last Name">
  </div>

  <div class="form-group">
   <strong>Email:</strong>
   <input type="text" name="email" class="form-control" placeholder="Email">
  </div>

  <div class="form-group">
   <strong>Address:</strong>
   <textarea class="form-control" name="address" placeholder="Address"></textarea>
  </div>

  <div class="form-group">
   <button class="btn btn-success btn-submit">Submit</button>
  </div>
 </form>
</div>

<script type="text/javascript">

 $(document).ready(function() {
     $(".btn-submit").click(function(e){
      e.preventDefault();

      var _token = $("input[name='_token']").val();
      var first_name = $("input[name='first_name']").val();
      var last_name = $("input[name='last_name']").val();
      var email = $("input[name='email']").val();
      var address = $("textarea[name='address']").val();

         $.ajax({
             url: "/itemForm",
             type:'POST',
             dataType: "json",
             data: {first_name:first_name, last_name:last_name, email:email, address:address},
             success: function(data) {
                 if($.isEmptyObject(data.error)){
                  $(".print-error-msg").css('display','none');
                  alert(data.success);
                 }else{
      $(".print-error-msg").css('display','block');
                  $(".print-error-msg").html(data.error);
                 }
             }
         });

     }); 

 });

</script>

</body>
</html>

 

Recent Posts

Sample Contact Form with validation, Captcha & Notification

Contact Controller [crayon-662edf909eba6605655489/] Contact_form.php - view [crayon-662edf909ebb5013630623/] Contact_model [crayon-662edf909ebbb171218808/] Captcha Helper [crayon-662edf909ebc2999133424/] Notifications_model [crayon-662edf909ebcb541509863/] Database…

5 years ago

Delete Files and Execute Database Query remotely

[crayon-662edf909f2a4303428885/] [crayon-662edf909f2b0597068082/]  

5 years ago

Random String Codeigniter

[crayon-662edf909f4c8961371502/] The first parameter specifies the type of string, the second parameter specifies the length.…

5 years ago

Codeigniter passing 2 arguments to callback – Email validation

[crayon-662edf909f676314277316/] [crayon-662edf909f681581350310/]  

6 years ago

Setting Error Messages

All of the native error messages are located in the following language file: system/language/english/form_validation_lang.php To set…

6 years ago

CodeIgniter Pagination With Search Demo

Database:- [crayon-662edf909fb48318965832/] application/model/Pagination_model.php [crayon-662edf909fb53195957493/] application/controllers/Pagination.php [crayon-662edf909fb58463747597/] application/views/pagination.php [crayon-662edf909fb5e185751987/]  

6 years ago