Ajax contact us form validation in Codeigniter 3 using javascript jQuery

Ajax contact us form validation in Codeigniter 3 using javascript jQuery

In this Codeigniter Tutorial, I am going to tell you how to validate contact us form using Ajax.

I am going to use Codeigniter Form Validation class to validate contact us form, If the error exists then It will display the proper validation errors.

I will use jQuery to avoid complete page refresh on form submission in Codeigniter.

For this example, I will create simple HTML contact us form and implement server-side validation rules in Codeigniter on form submission using Ajax.

Step1: Add Routes

In this step, I will add routes to handle ajax request and display the form.

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


$route['default_controller'] = 'welcome';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;

$route['ajax-form-validate'] = "AjaxFormValidate";
$route['ajax-form-validate/post']['post'] = "AjaxFormValidate/validateForm";
Step2: Create AjaxFormValidate Controller Class

In this step, I will create a controller "AjaxFormValidate.php" in following path application/controllers/

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


class AjaxFormValidate 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('ajax_form_validate');
   }


   /**
    * Validate and store the form data.
    *
    * @return Response
   */
   public function validateForm()
   {
        $this->form_validation->set_rules('name', 'Name', 'required');
        $this->form_validation->set_rules('email', 'Email', 'required|valid_email');
        $this->form_validation->set_rules('message', 'Message', 'required');


        if ($this->form_validation->run() == FALSE){
            $errors = validation_errors();
            echo json_encode(['error'=>$errors]);
        }else{
           echo json_encode(['success'=>'Form submitted successfully.']);
        }
    }
}
Step3: Create View File (ajax_form_validate.php)

In this step, I will create a simple HTML form using form_open() helper method in Codeigniter.

I will include jQuery and Bootstrap library and send the ajax request with form data on the server to implement validation rules.

<html>
  <head> 
    <title>Ajax contact us form validation in Codeigniter using javascript jQuery</title>
     <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.min.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  </head>
  <body> 
  <div class="container">
    <div class="row">
      <div class="col-sm-8 col-sm-offset-2">
        <div class="alert alert-danger" style="display:none">
        </div>

      <?php echo form_open('ajax-form-validate/post');?> 
        <div class="form-group">
          <label>Name:</label>
          <input type="text" name="name" class="form-control" placeholder="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>Message:</strong>
          <textarea class="form-control" name="message" placeholder="Message"></textarea>
        </div>

        <div class="form-group">
          <button class="btn btn-primary btn-block btn-submit">Submit</button>
        </div>
      </form>
    </div>
    </div>
  </div>
   </body>


   <script type="text/javascript">
    $(document).ready(function() {
      $(".btn-submit").click(function(e){
        e.preventDefault();
        var name = $("input[name='name']").val();
        var email = $("input[name='email']").val();
        var message = $("textarea[name='message']").val();

        console.log($(this).closest('form').attr('action'));
          $.ajax({
              url: $(this).closest('form').attr('action'),
              type:$(this).closest('form').attr('method'),
              dataType: "json",
              data: {name:name, email:email, message:message},
              success: function(data) {
                  if($.isEmptyObject(data.error)){
                    $(".alert-danger").css('display','none');
                    alert(data.success);
                  }else{
                    $(".alert-danger").css('display','block');
                    $(".alert-danger").html(data.error);
                  }
              }
          });


      }); 


  });

   </script>


</html>

Phone: (+91) 8800417876
Noida, 201301
Betwinner
pendik escort
kartal escort