Tutorial Validasi Codeigniter dengan Ajax Server Side

Validasi form pada web ada dua jenis di client side (sisi klien) dan server side (sisi klien). Tentu berdasarkan performa untuk validasi form server side lebih unggul di banding client side, silahkan googling sendiri perbedaan validasi Client Side dan Server Side  ^_^.
Validasi CodeIgniter Server Side With Ajax
Validasi CodeIgniter Server Side With Ajax

Disini akan dibahas Tutorial cara melakukan validasi form CodeIgniter menggunakan Server Side (Sisi Server) dengan Ajax. Untuk kategori validasinya sendiri terdiri beberapa kategori yaitu :
  • field tidak boleh kosong
  • field tidak boleh sama dengan sudah di input (!=duplikat input)
  • input hanya boleh number saja, dengan maksimal dan minimal karakter.
  • validasi email yang valid.
Owh yah.. pada Tutorial Form Validation CodeIgniter dengan Ajax Server Side, saya menggunakan CodeIgniter versi 3 dan juga framework Bootstrap 3.

Untuk alur Validasi CodeIgniter dengan Ajax Server Side :
  1. Input data field 
  2. Data akan di proses menggunakan Ajax (Ajax mengirim ke Server Side)
  3. Server Side akan cek data, apakah kosong ? duplikat data ? Angaka atau huruf ? Minimal dan Maksimal karakter ?
  4. Jika cek Validasi Server Side berhasil, Server Side akan konfirmasi ke Ajax dan Ajax menampilakan pesan berhasil
  5. Jika cek Validasi Server Side gagal, Server Side akan konfirmasi ke Ajax berupa input field tidak memenuhi syarat, dan Ajax menampilkan pesan syarat yang harus dipenuhi.
Berikut Coding untuk view saya di bagi menjadi 5 yaitu head.php, nav.php, form.php content.php dan footer.php

Coding untuk head.php => berupa data css dan js 
<!doctype html>
<html lang="en">
  <head>
    <title><?php echo $title;?></title>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" type="text/css" href="<?php echo base_url();?>asset/bootstrap.min.css">             
    <link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" />  
   <!-- Javascripts-->
    <script src="<?php echo base_url();?>asset/jquery.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>  
    <script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>  
    <script src="<?php echo base_url();?>asset/bootstrap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootbox.js/4.4.0/bootbox.min.js"></script>
     
  </head>
  
Coding untuk nav.php => data coding untuk navbar menu
<nav class="navbar navbar-default">
  <div class="container-fluid">
    <div class="navbar-header">
      <a class="navbar-brand" href="#">CodeIgniter 3</a>
    </div>
    <ul class="nav navbar-nav">
      <li><a href="<?php echo base_url();?>">Home</a></li>
      <li><a href="<?php echo base_url();?>home/content">Data</a></li>            
    </ul>
  </div>
</nav>
Coding untuk form.php => data coding form input field
 <body>
   <div class="container">
  <div class="row">

    <div class="col-sm-4"></div>
    <div class="col-sm-4">
    <h3>Crud Insert Data</h3><hr/>

 <div id="info"></div>
  <?php echo form_open('home/data', 'id="mydata" '); ?>
  <div class="form-group">    
    <input type="text" class="form-control" name="nim" id="nim" placeholder="Enter NIM">    
  </div>
    <div class="form-group">    
    <input type="text" class="form-control" name="username" id="username" placeholder="Enter Nama">
    <small id="NamaHelp" class="form-text text-muted">Masukan nama lengkap anda.</small>
  </div>
  <div class="form-group">    
    <input type="email" class="form-control" name="email" id="email" placeholder="Enter email">
  </div>
  <button type="submit" class="btn btn-primary">Save</button>
</form>

    </div>
    <div class="col-sm-4"></div>

  </div>
</div>
  
<script type="text/javascript">
  $('#mydata').submit(function(e){
    e.preventDefault();
     var fa = $(this);

      $.ajax({
        url: fa.attr('action'),
        type: 'post' ,
        data: fa.serialize(),
        dataType: 'json',
        success: function(response) {
          if(response.success == true) {
            $('#info').append('<div class="alert alert-success">' + 
              'Data Tersimpan' + '</div>');
            $('.form-group').removeClass('has-error')
                            .removeClass('has-success');
            $('.text-danger').remove();
            fa[0].reset();

            $('.alert-success').delay(500).show(10, function() {
                $(this).delay(3000).hide(10, function() {
                    $(this).remove();
                });
            })

          } else {
            $.each(response.messages,function(key, value){
              var element = $('#' + key);
              element.closest('div.form-group')
              .removeClass('has-error')
              .addClass(value.length > 0 ? 'has-error' : 'has-success')
              .find('.text-danger')
              .remove();
              element.after(value);
            });
          }
        }
     });

  });
 </script>

Untuk tampil data saya menggunakan DataTable Server Side, jadi Tutorial ini bisa juga di gunakan untuk Tampil data CodeIgniter 3 menggunakan DataTable Server Side.

Coding untuk content.php => data coding untuk tampil data
  <body>
  <div class="container">
  <h3>Crud Edit & Delete</h3><hr/>
<div id="info"></div>
   <div class="table-responsive">                                 
     <table id="user_data" class="table table-bordered table-striped">  
      <thead>  
           <tr>  
                <th>NIM</th>  
                <th>Nama</th>  
                <th>Email</th>
                <th>Edit</th>                                                                 
                <th>Delete</th>
           </tr>  
      </thead>  
        </table>  
      </div>  
  </div>    

    <div id="userModal" class="modal fade">  
      <div class="modal-dialog">


     <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">Edit Data</h4></br>
          <div class="alert alert-danger"><strong>Maaf...</strong> Masih dalam tahap pengembangan&nbsp;&nbsp;^_^</div>
        </div>
        <div class="modal-body">
          
     <?php echo form_open('#', 'id="mydata" '); ?>
      <div class="form-group">    
        <input type="text" class="form-control" name="nim" id="nim" placeholder="Enter NIM" readonly/>    
      </div>
        <div class="form-group">    
        <input type="text" class="form-control" name="nama" id="nama" placeholder="Enter Nama">
        <small id="NamaHelp" class="form-text text-muted">Masukan nama lengkap anda.</small>
      </div>
      <div class="form-group">    
        <input type="email" class="form-control" name="email" id="email" placeholder="Enter email">
      </div>
      <button type="submit" class="btn btn-primary" disabled>Update</button>
    </form>

        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>

    </div>
</div>      
                   

 <script type="text/javascript" language="javascript">
 $(document).ready(function(){  
      var dataTable = $('#user_data').DataTable({  
           "processing":true,  
           "serverSide":true,  
           "order":[],  
           "ajax":{  
                url:"<?php echo base_url() .'home/datauser'; ?>",  
                type:"POST"  
           },  
           "columnDefs":[  
                {  
                     "targets":[0, 3, 4],  
                     "orderable":false,  
                },  
           ],  
      });  

  $(document).on("click", ".delete", function(e) {
           var nim = $(this).attr("id"); 
           e.preventDefault();
           bootbox.confirm("Are you sure delete ?", function(result) {
               if (result) {

                     $.ajax({  
                     url:"<?php echo base_url(); ?>home/delete_nim",  
                     method:"POST",  
                     data:{nim:nim},  
                     success:function(data)  
                     {                            
                          dataTable.ajax.reload();  
                     }  
                });

               }   
           });
       });

       $(document).on('click', '.update', function(){  
           var nim = $(this).attr("id");  
           $.ajax({  
                url:"<?php echo base_url(); ?>home/danim",  
                method:"POST",  
                data:{nim:nim},  
                dataType:"json",  
                success:function(data)  
                {  
                     $('#userModal').modal('show');  
                     $('#nim').val(data.nim);  
                     $('#nama').val(data.nama);
                     $('#email').val(data.email);  
                }  
           })  
      }); 
     
 });  

 </script>  
 

Coding untuk footer.php => data coding penutup tag 
  </body>
</html>

Untuk model coding saya berinama file mdata.php
Coding untuk mdata.php
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
Class Mdata extends CI_Model
{
   var $table = "tbmhs";  
      var $select_column = array("id", "nim", "nama", "email");  
      var $order_column = array(null, "nim", "nama", null, null);  

  //query insert data
  function insert_all($table,$data) {
    $this->db->insert($table,$data);
  }

    function update_all($where,$data,$table) {
    $this->db->where($where);
    $this->db->update($table,$data);
  }

  // chech or ambil all data
 function check_all($table,$where,$limit) {
  $query = $this->db->get_where($table,$where,$limit);
  if($query->num_rows()==1)
  {
   return $query->result();
  }
  else {
   return false;
  }
 }

      function make_query()  
      {  
           $this->db->select($this->select_column);  
           $this->db->from($this->table);  
           if(isset($_POST["search"]["value"]))  
           {  
                $this->db->like("nim", $_POST["search"]["value"]);  
                $this->db->or_like("nama", $_POST["search"]["value"]);  
           }  
           if(isset($_POST["order"]))  
           {  
                $this->db->order_by($this->order_column[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);  
           }  
           else  
           {  
                $this->db->order_by('nim', 'DESC');  
           }  
      }  
      function make_datatables(){  
           $this->make_query();  
           if($_POST["length"] != -1)  
           {  
                $this->db->limit($_POST['length'], $_POST['start']);  
           }  
           $query = $this->db->get();  
           return $query->result();  
      }  
      function get_filtered_data(){  
           $this->make_query();  
           $query = $this->db->get();  
           return $query->num_rows();  
      }       
      function get_all_data()  
      {  
           $this->db->select("*");  
           $this->db->from($this->table);  
           return $this->db->count_all_results();  
      }

          function delete_data($nim)  
      {  
           $this->db->where("nim", $nim);  
           $this->db->delete("tbmhs");  
           //DELETE FROM users WHERE id = '$user_id'  
      }   
 }

?>


Untuk Controller coding saya berinama file home.php
Coding untuk home.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Home extends CI_Controller {

 function __construct()
 {
 parent::__construct();
 $this->load->model('mdata', '', TRUE);
 $this->load->helper(array('form', 'url'));
 }

 public function index()
 {
  $data['title'] = "Form Crud";
  $data['active'] = "active";
  $this->load->view('head',$data);
  $this->load->view('nav');
  $this->load->view('form');
  $this->load->view('footer');  
 }

 public function content()
 {
  $data['title'] = "Data Crud";
  $data['active'] = "active";
  $this->load->view('head',$data);
  $this->load->view('nav');
  $this->load->view('content');
  $this->load->view('footer');  
 }


 public function data() {

  $data = array ('success' => false, 'messages' => array());

  $this->load->library('form_validation');
  $this->form_validation->set_rules('nim', 'Nim', 'trim|required|numeric|min_length[10]|max_length[11]|callback_nimdata_check'); 
  $this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[5]|max_length[12]|callback_namadata_check');    
  $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|is_unique[tbmhs.email]');  
  $this->form_validation->set_error_delimiters('<p class="text-danger">', '</p>');


  if($this->form_validation->run()) {   


    $data = array (
       'nim' => $this->input->post('nim'),
       'nama' => $this->input->post('username'),
       'email' => $this->input->post('email')        
     );
    $this->mdata->insert_all('tbmhs',$data);
    
   $data['success'] = true;

  } else {
   foreach ($_POST as $key => $value) {
     $data['messages'][$key] = form_error($key);
   }   

  }
  echo json_encode($data);

 }


        public function nimdata_check($nim)
        {

         $where = array ('nim'=>$nim);
   $check = $this->mdata->check_all('tbmhs',$where,1);

                if ($check)
                {
                        $this->form_validation->set_message('nimdata_check', 'The {field} already exists');
                        return FALSE;
                }
                else
                {
                        return TRUE;
                }
        }

        public function namadata_check($str)
        {

         $where = array ('nama'=>$str);
   $check = $this->mdata->check_all('tbmhs',$where,1);

                if ($check)
                {
                        $this->form_validation->set_message('namadata_check', 'The {field} already exists');
                        return FALSE;
                }
                else
                {
                        return TRUE;
                }
        }


        function datauser() {             
           $fetch_data = $this->mdata->make_datatables();  
           $data = array();  
           foreach($fetch_data as $row)  
           {  
                $sub_array = array();                  
                $sub_array[] = $row->nim;  
                $sub_array[] = $row->nama;
                $sub_array[] = $row->email;  
                $sub_array[] = '<button type="button" name="update" id="'.$row->nim.'" class="btn btn-info btn-xs update">Update</button>';  
                $sub_array[] = '<button type="button" name="delete" id="'.$row->nim.'" class="btn btn-danger btn-xs delete">Delete</button>';  
                $data[] = $sub_array;  
           }  
           $output = array(  
                "draw"                    =>     intval($_POST["draw"]),  
                "recordsTotal"          =>      $this->mdata->get_all_data(),  
                "recordsFiltered"     =>     $this->mdata->get_filtered_data(),  
                "data"                    =>     $data  
           );  
           echo json_encode($output);  
      }  


        function delete_nim()  
      {             
           $this->mdata->delete_data($_POST["nim"]);             
      } 


         function danim()  
      {  

           $output = array();             
           $data = $this->mdata->check_all('tbmhs', array('nim'=>$_POST["nim"]),1);           
           foreach($data as $row)  
           {  
                $output['nim'] = $row->nim;  
                $output['nama'] = $row->nama;
                $output['email'] = $row->email;  
           }  
           echo json_encode($output);  
      }  
  
}

Silahkan jalankan di localhost atau mau upload hosting free untuk demo mangga ^_^....
Demikian tutorial cara validasi form CodeIgniter 3 dengan Ajax Server Side atau Tutorial cara menampilkan data CodeIgniter 3 dengan DataTable Server Side.
Untuk Demo Review video => Youtube Demo
Link Download Coding zip di Sini
Semoga bermanfaat terima kasih, jika ada pertanyaan silahkan tinggalkan jejak di form komentar ^_^



Comments

Post a Comment