Saturday 27 April 2019

Ajax Form Validation in Codeigniter with JSON



If you not know how to validate form data by using Codeigniter Form validation library by using Ajax and receive response in JSON data type. In this post you can find Form validation in Codeignter by using Ajax jQuery and JSON. For learn Codeigniter Form Validation library with Ajax, here we will make codeigniter ajax contact form for learn this topic.

We have already learn many thing in Codeigniter framework with Ajax. In this post we have share interesting topic on Codeigniter with Ajax and here you can find how to create Ajax jQuery form validation in Codeigniter framework. With help of Codeigniter Form validation library with Ajax, we will received success or error message in JSON format.

Every programmer know validation is a very important part of any web based application or any type of Software process. Because in every web application you can find form like login form, registration form, contact us form comment form etc, so we want to validate form data, if we have not validate form data then it is very dangerous for our web application. If you have use Codeigniter framework for your web based application then Codeigniter has rich form validation library for validate form data, which set server side validation. But server side form data validation has refresh page on every form submission. So, We want to prevent to refresh form, we have to use Ajax with Codeigniter form validation library. Which has been send ajax request to Codeigniter method which will perform validation rules on form data by using Form Validation library. If there is any validation error occur then by using form_error() method it will fetch validation error and store under array and send to back to ajax request in JSON format.

So, Form submission process will be done without refresh of web page. Here you can also find how to submit form in codeigniter by using Ajax without refresh of web page. For learn this topic here we will make contact form with field like name, email address, subject and message. This contact form data will be send to Codeigniter method by using Ajax. In Codeigiter method it will perform different validation rules like required field validation, email format validation by using codeigniter form validation library. And after success of validation rules then it will send response to ajax in json format. Below you can find complete source code of Codeigniter Ajax Form validation.





Source Code


Form_validation.php (Controllers)



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

class Form_validation extends CI_Controller {

 function index()
 {
  $this->load->view('form_validation');
 }

 function validation()
 {
  $this->load->library('form_validation');
  $this->form_validation->set_rules('name', 'Name', 'required');
  $this->form_validation->set_rules('email', 'Email', 'required|valid_email');
  $this->form_validation->set_rules('subject', 'Subject', 'required');
  $this->form_validation->set_rules('message', 'Message', 'required');
  if($this->form_validation->run())
  {
   $array = array(
    'success' => '<div class="alert alert-success">Thank you for Contact Us</div>'
   );
  }
  else
  {
   $array = array(
    'error'   => true,
    'name_error' => form_error('name'),
    'email_error' => form_error('email'),
    'subject_error' => form_error('subject'),
    'message_error' => form_error('message')
   );
  }

  echo json_encode($array);
 }

}

?>


form_validation.php (Views)



<html>
<head>
    <title>Codeigniter Form Validation using Ajax JSON</title>
    
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>    
</head>
<body>
 <div class="container">
  <br />
  <h3 align="center">Codeigniter Form Validation using Ajax JSON</h3>
  <br />
  <div class="row">
   <div class="col-md-4">

   </div>
   <div class="col-md-4">
    <span id="success_message"></span>
    <form method="post" id="contact_form">
     <div class="form-group">
      <input type="text" name="name" id="name" class="form-control" placeholder="Name" />
      <span id="name_error" class="text-danger"></span>
     </div>
     <div class="form-group">
      <input type="text" name="email" id="email" class="form-control" placeholder="Email Address" />
      <span id="email_error" class="text-danger"></span>
     </div>
     <div class="form-group">
      <input type="text" name="subject" id="subject" class="form-control" placeholder="Subject">
      <span id="subject_error" class="text-danger"></span>
     </div>
     <div class="form-group">
      <textarea name="message" id="message" class="form-control" placeholder="Message" rows="6"></textarea>
      <span id="message_error" class="text-danger"></span>
     </div>
     <div class="form-group">
      <input type="submit" name="contact" id="contact" class="btn btn-info" value="Contact Us">
     </div>
    </form>
   </div>
   <div class="col-md-4"></div>
  </div>
 </div>
</body>
</html>
<script>
$(document).ready(function(){

 $('#contact_form').on('submit', function(event){
  event.preventDefault();
  $.ajax({
   url:"<?php echo base_url(); ?>form_validation/validation",
   method:"POST",
   data:$(this).serialize(),
   dataType:"json",
   beforeSend:function(){
    $('#contact').attr('disabled', 'disabled');
   },
   success:function(data)
   {
    if(data.error)
    {
     if(data.name_error != '')
     {
      $('#name_error').html(data.name_error);
     }
     else
     {
      $('#name_error').html('');
     }
     if(data.email_error != '')
     {
      $('#email_error').html(data.email_error);
     }
     else
     {
      $('#email_error').html('');
     }
     if(data.subject_error != '')
     {
      $('#subject_error').html(data.subject_error);
     }
     else
     {
      $('#subject_error').html('');
     }
     if(data.message_error != '')
     {
      $('#message_error').html(data.message_error);
     }
     else
     {
      $('#message_error').html('');
     }
    }
    if(data.success)
    {
     $('#success_message').html(data.success);
     $('#name_error').html('');
     $('#email_error').html('');
     $('#subject_error').html('');
     $('#message_error').html('');
     $('#contact_form')[0].reset();
    }
    $('#contact').attr('disabled', false);
   }
  })
 });

});
</script>





10 comments:

  1. This code have really helped me a lot. Thank you very much. It works just perfect.

    ReplyDelete
  2. i want to create multiform wizard with codeigniter form validation.. is it possible?

    ReplyDelete
  3. How about one of each field is input with type"file", can u make a tutorial please?
    i've tried a lot of ways. but still doesn't work like what i want it to be. Thank you so much

    ReplyDelete
  4. Thanks man. You give a lot inspiration for more complexe solutions. Great stuff!

    ReplyDelete
    Replies
    1. can u mail form validation code using ajax & jQuery using CI. zukizu77@gmail.com
      Thanks

      Delete
  5. Great tutorial, will use it validate my forms. Nice work done

    ReplyDelete
  6. Can you please make codeigniter 3 login and registration rest api with jwt? It will be greate and very helpfull for us. Thanks

    ReplyDelete