Codeigniter jQuery Ajax Form Submit with Validation

Jquery submit form ajax in Codeigniter without refresh whole page with validate form data on client side. We will discuss how to submit a form using ajax without refresh or reload whole page, we will use jquery submit handler with jquery validation rules for ajax form submission.

In this ajax form submit article, you will learn very simple method to submit a form without refresh whole page with validate form data in client side from scratch .

Contents

  • Download Codeigniter Project
  • Basic Configurations
  • Create Database With Table
  • Setup Database Credential
  • Create Controller
  • Make Model
  • Create Views
  • Start Development server
  • Conclusion

Download Codeigniter Project

In this step we will download the latest version of Codeigniter, Go to this link Download Codeigniter. Download the fresh setup of codeigniter and unzip the setup in your local system xampp/htdocs/ and also rename your project folder name as you want.

Basic Configurations

Next we will set the some basic configuration on config.php file, so let’s go to application/config/config.php and open this file on text editor.

 
Set Base URL like this

$config['base_url'] = 'http://localhost/your_project_name';

Create Database With Table

In this step, we need to create database name ci_database, so let’s open your phpmyadmin and create the database with the name ci_database. After successfully create a database, you can use the below sql query for creating a table in your database.

CREATE TABLE users (
id int(10) UNSIGNED NOT NULL,
name varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
email varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
mobile_number varchar(50) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

Setup Database Credential

Next step, we will connect the crud_app project with database, so go to application/database.php and setup the database credential here. In this file add your database name, username and password.

$db['default'] = array(
	'dsn'	=> '',
	'hostname' => 'localhost',
	'username' => 'root',
	'password' => '',
	'database' => 'ci_database',
	'dbdriver' => 'mysqli',
	'dbprefix' => '',
	'pconnect' => FALSE,
	'db_debug' => (ENVIRONMENT !== 'production'),
	'cache_on' => FALSE,
	'cachedir' => '',
	'char_set' => 'utf8',
	'dbcollat' => 'utf8_general_ci',
	'swap_pre' => '',
	'encrypt' => FALSE,
	'compress' => FALSE,
	'stricton' => FALSE,
	'failover' => array(),
	'save_queries' => TRUE
);

Create Controller

Go to application/controllers/ and create a controller name Ajax.php. In this controller we will create some method/function name create and store for showing and storing form data.

<?php
class Ajax extends CI_Controller {
 
    public function __construct()
    {
        parent::__construct();
        $this->load->model('Form_model');
        $this->load->helper('url_helper');
        $this->load->helper('form');
        $this->load->library('form_validation');
    }
    public function create()
    {
        $data['title'] = 'jQuery Ajax Form';
        $this->load->view('jquery-ajax/jquery-ajax-form', $data);
    }
    public function store()
    {

        $insert = $this->Form_model->create();

        $data = array('success' => false, 'msg'=> 'Form has been not submitted');
        if($insert){
        $data = array('success' => true, 'msg'=> 'Form has been submitted successfully');
        }

        echo json_encode($data);
        
    }
    
}

Make Model

Go to application/models/ and create model name Form_model.php. In this form model, we will write code for storing a form data into database.

<?php
class Form_model extends CI_Model {
 
    public function __construct()
    {
        $this->load->database();
    }
    
    
    public function create()
    {
        $this->load->helper('url');

        $data = array(
            'name' => $this->input->post('name'),
            'mobile_number' => $this->input->post('mobile_number'),
            'email' => $this->input->post('email')
        );
        $insert = $this->db->insert('users', $data);
        if ($insert) {
           return $this->db->insert_id();
        } else {
            return false;
        }
    }
}

Create Views

Go to application/views/ and create a one view name ajax-form.php.

In this ajax form, we will implement jquery submit handler. first we will validate form using jquery validation and second is submit a ajax form using submit handler.

<!doctype html>
<html lang="en">
  <head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>Codeigniter Ajax Form Submission Example - Tutsmake.com</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/additional-methods.min.js"></script>
  <style>
   .error{ color:red; } 
  </style>
</head>
 
<body>
 
<div class="container">
    <h2 style="margin-top: 10px;">Codeigniter Ajax Form Submission Example - <a href="https://www.tutsmake.com" target="_blank">TutsMake</a></h2>
    <br>
    <br>
   
    <form id="ajax_form" method="post" action="javascript:void(0)">
      <div class="form-group">
        <label for="formGroupExampleInput">Name</label>
        <input type="text" name="name" class="form-control" id="formGroupExampleInput" placeholder="Please enter name">
      </div>

      <div class="form-group">
        <label for="email">Email Id</label>
        <input type="text" name="email" class="form-control" id="email" placeholder="Please enter email id">
      </div>   

      <div class="form-group">
        <label for="mobile_number">Mobile Number</label>
        <input type="text" name="mobile_number" class="form-control" id="mobile_number" placeholder="Please enter mobile number" maxlength="10">
      </div>

      <div class="alert alert-success d-none" id="msg_div">
          <span id="res_message"></span>
      </div>

      <div class="form-group">
       <button type="submit" id="send_form" class="btn btn-success">Submit</button>
      </div>
    </form>
 
</div>
</body>
</html>

Now we need to create script code for submitting form data using jQuery ajax with jQuery validation.

<script>
   if ($("#ajax_form").length > 0) {
    $("#ajax_form").validate({
     
    rules: {
      name: {
        required: true,
        maxlength: 50
      },
 
       mobile_number: {
            required: true,
            digits:true,
            minlength: 10,
            maxlength:12,
        },
        email: {
                required: true,
                maxlength: 50,
                email: true,
            },    
    },
    messages: {
       
      name: {
        required: "Please enter name",
        maxlength: "Your last name maxlength should be 50 characters long."
      },
      mobile_number: {
        required: "Please enter contact number",
        minlength: "The contact number should be 10 digits",
        digits: "Please enter only numbers",
        maxlength: "The contact number should be 12 digits",
      },
      email: {
          required: "Please enter valid email",
          email: "Please enter valid email",
          maxlength: "The email name should less than or equal to 50 characters",
        },
        
    },
    submitHandler: function(form) {
      $('#send_form').html('Sending..');
      $.ajax({
        url: "<?php echo base_url('ajax/store') ?>",
        type: "POST",
        data: $('#ajax_form').serialize(),
        dataType: "json",
        success: function( response ) {
            console.log(response);
            console.log(response.success);
            $('#send_form').html('Submit');
            $('#res_message').html(response.msg);
            $('#res_message').show();
            $('#msg_div').removeClass('d-none');

            document.getElementById("ajax_form").reset(); 
            setTimeout(function(){
            $('#res_message').hide();
            $('#msg_div').hide();
            },10000);
        }
      });
    }
  })
}
</script>

The above code put on the form after closing a body tag.

Start Development server

We will hit the below url in browser and run our created project.

http://localhost/your_project_name/ajax/create

Conclusion

In this codeigniter ajax form submit tutorial – We have successfully created created a form and submit the form using jQuery ajax without reload the whole page.

One Comment

  1. MW Ehtisham said:

    exellent sir (Y)

    July 25, 2019
    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *