Ajax form submission with validation in CodeIgniter 4; In this tutorial guide, you will learn how to submit a form and insert form data into mysql database using ajax without page refresh in CodeIgniter 4 projects.
In this tutorial guide, we will create a contact form and submit the contact form using Ajax and validate it before sending the form data to the server in CodeIgniter 4. And this contact form will send data to the server without refreshing the whole page and Also, the form will insert the data into the database in CodeIgniter 4 framework using ajax.
How To Submit and Insert Form Data Using Ajax jQuery with Validation In CodeIgniter 4 Apps
Follow the below steps to submit and insert form data using jQuery Ajax with validation and without reloading the whole page in CodeIgniter 4 projects:
- Step 1: Setup Codeigniter Project
- Step 2: Basic Configurations
- Step 3: Create a Database and Tables
- Step 4: Setup Database Credentials
- Step 5: Create Model and Controller
- Step 5: Create Views
- Step 6: Start Development server
Step 1: Setup Codeigniter Project
In this step, we will download the latest version of Codeigniter 4, Go to this link https://codeigniter.com/download Download Codeigniter 4 fresh new setup and unzip the setup in your local system xampp/htdocs/ . And change the download folder name “demo”
Step 2: Basic Configurations
Next, we will set some basic configuration on the app/config/app.php file, so let’s go to application/config/config.php and open this file on text editor.
Set Base URL like this
public $baseURL = 'http://localhost:8080'; To public $baseURL = 'http://localhost/demo/';
Step 3: Create a Database and Tables
In this step, we need to create a database name demo, so let’s open your PHPMyAdmin and create the database with the name demo. After successfully create a database, you can use the below SQL query for creating a table in your database.
CREATE TABLE contacts ( id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key', name varchar(100) NOT NULL COMMENT 'Name', email varchar(255) NOT NULL COMMENT 'Email Address', message varchar(250) NOT NULL COMMENT 'Message', created_at varchar(20) NOT NULL COMMENT 'Created date', PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='demo table' AUTO_INCREMENT=1;
Step 4: Setup Database Credentials
In this step, we need to connect our project to the database. we need to go app/Config/Database.php and open database.php file in text editor. After opening the file in a text editor, We need to set up database credentials in this file like below.
public $default = [ 'DSN' => '', 'hostname' => 'localhost', 'username' => 'root', 'password' => '', 'database' => 'demo', 'DBDriver' => 'MySQLi', 'DBPrefix' => '', 'pConnect' => false, 'DBDebug' => (ENVIRONMENT !== 'production'), 'cacheOn' => false, 'cacheDir' => '', 'charset' => 'utf8', 'DBCollat' => 'utf8_general_ci', 'swapPre' => '', 'encrypt' => false, 'compress' => false, 'strictOn' => false, 'failover' => [], 'port' => 3306, ];
Step 5: Create Model and Controller
So go to app/Models/ and create here one model. And you need to create one model name contactModel.php and update the following code into your contactModel.php file:
<?php namespace App\Models; use CodeIgniter\Database\ConnectionInterface; use CodeIgniter\Model; class ContactModel extends Model { protected $table = 'contacts'; protected $allowedFields = ['name', 'email', 'message']; }
Create Controller
Now Go to app/Controllers and create a controller name Contact.php. In this controller, we will create some method/function. We will build some of the methods like :
- Index() – This is used to display contact us form.
- create() – This is used to validate form data server-side and store into mysql database.
<?php namespace App\Controllers; use CodeIgniter\Controller; use App\Models\ContactModel; class Contact extends Controller { public function index() { return view('contact'); } public function create() { helper(['form', 'url']); $db = \Config\Database::connect(); $builder = $db->table('contacts'); $data = [ 'name' => $this->request->getVar('name'), 'email' => $this->request->getVar('email'), 'message' => $this->request->getVar('message') ]; $save = $builder->insert($data); $data = [ 'success' => true, 'data' => $save, 'msg' => "Thanks for contact us. We get back to you" ]; return $this->response->setJSON($data); } }
Step 6: Create Views
Now we need to create contact.php, go to application/views/ folder and create contact.php file. and update the following HTML into your files:
<!DOCTYPE html> <html> <head> <title>codeigniter 4 ajax insert form with validation</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/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> </head> <body> <div class="container"> <br> <?= \Config\Services::validation()->listErrors(); ?> <span class="d-none alert alert-success mb-3" id="res_message"></span> <div class="row"> <div class="col-md-9"> <form action="javascript:void(0)" name="ajax_form" id="ajax_form" method="post" accept-charset="utf-8"> <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="message">Message</label> <textarea name="message" class="form-control"></textarea> </div> <div class="form-group"> <button type="submit" id="send_form" class="btn btn-success">Submit</button> </div> </form> </div> </div> </div> <script> if ($("#ajax_form").length > 0) { $("#ajax_form").validate({ rules: { name: { required: true, }, email: { required: true, maxlength: 50, email: true, }, message: { required: true, }, }, messages: { name: { required: "Please enter name", }, email: { required: "Please enter valid email", email: "Please enter valid email", maxlength: "The email name should less than or equal to 50 characters", }, message: { required: "Please enter message", }, }, submitHandler: function(form) { $('#send_form').html('Sending..'); $.ajax({ url: "<?php echo base_url('contact/create') ?>", 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(); $('#res_message').removeClass('d-none'); document.getElementById("ajax_form").reset(); setTimeout(function(){ $('#res_message').hide(); $('#res_message').html(''); },10000); } }); } }) } </script> </body> </html>
This below line display error messages on your web page:
<?= \Config\Services::validation()->listErrors(); ?>
You need to add jQuery validation library given below in contact form:
<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>
When you include the jQuery validation library on contact us web page. After this, you will also have to write validation rules of jQuery on the contact page. Also, you need to write ajax form submit code. Which are given below:
<script> if ($("#ajax_form").length > 0) { $("#ajax_form").validate({ rules: { name: { required: true, }, email: { required: true, maxlength: 50, email: true, }, message: { required: true, }, }, messages: { name: { required: "Please enter name", }, email: { required: "Please enter valid email", email: "Please enter valid email", maxlength: "The email name should less than or equal to 50 characters", }, message: { required: "Please enter message", }, }, submitHandler: function(form) { $('#send_form').html('Sending..'); $.ajax({ url: "<?php echo base_url('public/index.php/contact/create') ?>", 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(); $('#res_message').removeClass('d-none'); document.getElementById("ajax_form").reset(); setTimeout(function(){ $('#res_message').hide(); $('#res_message').html(''); },10000); } }); } }) } </script>
Note:- And here jQuery validation rules and messages are written. You can also change these validation rules and error messages as per your requirements. And also you can change ajax request in Codeigniter 4 projects.
Step 7: Start Development server
For start development server, Go to the browser and hit below the URL.
http://localhost/demo/public/index.php/contact
Conclusion
In this Codeigniter 4 ajax form submit with jQuery validation tutorial, We have successfully validated form data on the client browser using the jQuery validation library and submit the form using ajax in CodeIgniter 4. and also validate form data on the server-side.
Recommended Codeigniter Posts
If you have any questions or thoughts to share, use the comment form below to reach us.