In this tutorial guide, we will learn how to submit a form using jQuery AJAX in CodeIgniter with form validation and without reloading the web page.
Submit form using AJAX in CodeIgniter with form validation
Here are steps:
- Download Codeigniter Project
- Set up BASE URL
- Create Database With Table
- Configure Database
- Create Controller
- Create Model
- Create View
- Test This Project
Download Codeigniter Project
In this step, we will download the latest version of Codeigniter from official Codeigniter website, and unzip the downloaded folder in local system.
Set up BASE URL
Setup base URL in application/config/config.php file:
$config['base_url'] = 'http://localhost/your_project_name';
Create Database With Table
Use the following SQL query to create table in database for this project:
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;
Configure Database
Edit database.php and add your database name, username and password in it:
$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
Create a controller name Ajax.php and methods in application/controllers folder to handle ajax form submission on server side:
<?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); } }
Create Model
Create Form_model.php in application/models/ that allow to insert form data into a database table:
<?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
Create a one view name ajax-form.php in application/views/ folder and form in to it to allow users to submit form using jQuery ajax on server:
<!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="//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>
Add the following jQuery AJAX script code on view file to validate and submit the form:
<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.
Test This Project
Open browser and use the following URL for testing:
http://localhost/your_project_name/ajax/create
Conclusion
That’s it, we have successfully created a form and submitted the form using jQuery AJAX without reloading the entire page.
exellent sir (Y)