Codeigniter 4 Ajax Form Submit Validation Example

Ajax form submit with validation in CodeIgniter 4. In this example tutorial, i will show you in detail on how to submit forms using ajax with jQuery validation in Codeigniter 4 apps. And also you will learn how jQuery validation rules work without refreshing the page.

As well as, also you will learn how to submit form using Ajax without page refresh in codeigniter 4 apps and how to store form data in database.

The jQuery validate js is a very powerful and easy to use client-side form validation plugin; it offers tons of customization options. It makes your validation work facile due to the wide array of validation options, and yes, it supports more than 35 languages.

If you are creating any form in codeigniter 4 app. And want to submit that form without refreshing the page and also want to add validation in it. So, in this tutorial, you will learn how to submit form using ajax with jQuery validation in codeigniter 4 apps.

For the CodeIgniter 4 ajax form submit with validation example , I’ll create a contact form and submit it using ajax with jQuery validation. And will submit form without reloading the whole web page using jQuery ajax in codeigniter 4 apps, as well as store data into database.

Codeigniter 4 Ajax Form Submit Validation Example

You can learn by following the steps given below on codeigniter 4 ajax form validation:

  • Install Codeigniter 4 Application
  • Basic App Configurations
  • Create Database and Table
  • Setup Database Credentials
  • Create Model and Controller
  • Create Views
  • Setup Routes
  • Start Development server

Step 1 – Install Codeigniter 4 Application

First of all, you need to ownload the latest version of Codeigniter 4. So, visit this link https://codeigniter.com/download Download Codeigniter 4 app and unzip the setup in your local system xampp/htdocs/ .

Note that, please change the download folder name “demo”.

Step 2 – Basic App Configurations

Now, you need to 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 Database and Table

Create a dataabase and table by executing the following SQL query:

CREATE DATABASE demo;

CREATE TABLE contacts(
    id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
    name varchar(150) NOT NULL COMMENT 'Name',
    email varchar(255) NOT NULL COMMENT 'Email',
    message varchar(250) NOT NULL COMMENT 'Message',
    created_at varchar(20) NOT NULL COMMENT 'Date Created',
    PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='contact form table' AUTO_INCREMENT=1;

Step 4 – Setup Database Credentials

To connect your codeigniter 4 app to the database. So, visit app/Config/ directory and open Database.php. Then add the databasae details like below into database.php file:

public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'test',
        'password' => '4Mu99BhzK8dr4vF1',
        'database' => 'demo',
        'DBDriver' => 'MySQLi',
        'DBPrefix' => '',
        'pConnect' => false,
        'DBDebug'  => (ENVIRONMENT !== 'development'),
        '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

Create ContactFormModel.php file, so visit app/Models/ directory and create ContactFormModel.php file. Then add the following code into your ContactFormModel.php file:

<?php 

namespace App\Models;
use CodeIgniter\Database\ConnectionInterface;
use CodeIgniter\Model;
 
class ContactFormModel extends Model
{
    protected $table = 'contacts';
    protected $allowedFields = [
        'name', 
        'email', 
        'message'
    ];
}

Create ContactFormController.php file. So, visit app/Controllers directory and create ContactFormController.php.Then add the following code into it:

<?php namespace App\Controllers;
 
use CodeIgniter\Controller;
use App\Models\ContactFormModel;
 
class ContactFormController extends Controller
{
    public function index()
    {    
         return view('contact_form');
    }
 
    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);
    }
}

The index() function renders the contact form template into the view.

The create() method handles the form of validation and contains various variables.

Step 6 – Create Views

Create contact_form.php view file, so visit application/views/ directory and create contact_form.php file. Then add the following HTML into contact_form.php file:

<!DOCTYPE html>
<html>

<head>
	<title>codeigniter 4 ajax form submit validation - Laratutorials.com</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>

Step 7 – Setup Routes

To define a route, So, visit app/Config/ directory and open Routes.php file. Then add the following routes into it:

$routes->setDefaultController('ContactFormController');
$routes->get('/', 'ContactFormController::index');

Note that, the routes will be displaying the contact form and submitting the data in the database on successful form submission.

Step 8 – Start Development server

Execute the following command into command prompt or terminal to start the codeigniter 4 application:

php spark serve

Then visit your web browser and hit the following url on it:

http://localhost/demo/

OR

http://localhost:8080/

Conclusion

CodeIgniter 4 Ajax jQuery form submit validation example tutorial. In this example,you have learned how to submit form using ajax with jquery validation rules with forms in Codeigniter 4 apps. And also will learned how to submit form using ajax without refreshing the page in codeigntier 4 apps.

Recommende CodeIgniter 4 Tutorial

  1. How to Install / Download Codeigniter 4 By Manual, Composer, Git
  2. How to Remove Public and Index.php From URL in Codeigniter 4
  3. Codeigniter 4 Form Validation Example Tutorial
  4. CodeIgniter 4 jQuery Form Validation Example Tutorial

Leave a Comment