Ajax provides a technique to handle the form request without reloading the page. You can use Ajax in CodeIgniter 4 for handling form data. This will allow you to validate and submit your form without refreshing it. This is used at the client-side to handle the client request in the browser. If you are working on PHP technology then while creating a web application, it is always required to use Ajax. Even you can handle the API request at the client-side using Ajax. Today, in this post, I will be showing you the use of Ajax in CodeIgniter 4. In this demo project, I will create a basic form and I will validate it. After the successful validation, it will be submitted on the given action through Ajax. Here, in the entire process, the form won’t refresh on the submit.
Prerequisites
We are going to work on CodeIgniter 4. Hence, in order to create a new project, you may download the setup directly from the official website of CodeIgniter. But, I will use composer dependency manager. So, you can ahead with composer, if you already installed it in your system.
Also, you will require the below configuration for the CodeIgniter 4 project setup.
- PHP >= 7.3
- MySQL (version > 5)
- Apache/Nginx Server
- VS Code Editor
- Composer
Create Project For Ajax Form Handling in Codeigniter 4
At the very first, open the terminal or command prompt whatever you have. Then hit the below command for installing the latest version of CodeIgniter.
composer create-project codeigniter4/appstarter ci4-ajax
The above command will take a couple of minutes to install the CodeIgniter project in your system. Once, it is done, you will need to configure the environment for the project.
Configure Project Environment in CodeIgniter 4
Before implementing any functionality in CodeIgniter 4, you will need to configure the environment. Therefore, open the project in the VS code editor. Now, inside the project directory, look for the env file. Initially, you will need to rename it to .env. Now, open this file and search for the Environment configuration inside the .env file.
Under the environment section, by default, the environment will be production. Hence, in order to work on the local system, this will require to be renamed as development.
#--------------------------------------------------------------------
# ENVIRONMENT
#--------------------------------------------------------------------
CI_ENVIRONMENT = development
In the next step, you will have to setup the database for the project. So, that we can work on the form handling and submitting the data into the table.
Login and Registration Authentication in Codeigniter 4
Configure Database in Codeigniter 4
Before going to the database configuration, create a database in MySQL first. After that come to the CodeIgniter 4 project. Again go inside the .env file and under the database section, configure the credentials as shown below.
#--------------------------------------------------------------------
# DATABASE
#--------------------------------------------------------------------
database.default.hostname = localhost
database.default.database = ci4_ajax
database.default.username = root
database.default.password = root
database.default.DBDriver = MySQLi
That’s it for the database configuration. Now, let’s create a migration file for the table(s).
Create a Migration in CodeIgniter 4
For creating a new migration, I will use the spark command. It will generate the migration file. I will create one table in which I will store some values using CodeIgniter AJAX form handling. Hence, let’s create a migration file using the below command. Open the terminal inside the project folder, and now hit the below command.
php spark make:migration ajaxForms
When the migration is created, it will return the below response.
Now, come to the app/Config/Database/Migrations folder and you will have the created migration file. In our case, we have the timestamp_Ajaxforms.php file.
Open that file, and replace it with the below schema.
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class Ajaxforms extends Migration
{
public function up()
{
$this->forge->addField([
'id' => [
'type' => 'INT',
'auto_increment' => true
],
'name' => [
'type' => 'VARCHAR',
'constraint' => '100'
],
'email' => [
'type' => 'VARCHAR',
'constraint' => '255'
],
'password' => [
'type' => 'VARCHAR',
'constraint' => '255'
],
'phone' => [
'type' => 'VARCHAR',
'constraint' => '255'
],
'address' => [
'type' => 'VARCHAR',
'constraint' => '255'
],
'created_at datetime default current_timestamp',
'updated_at datetime default current_timestamp on update current_timestamp'
]);
$this->forge->addKey('id', true);
$this->forge->createTable('ajaxForms');
}
public function down()
{
$this->forge->dropTable('ajaxForms');
}
}
Here, we defined the schema for the ajaxForms table. This table will need to be generated inside the database. Hence, in order to do that, you will need to migrate this table. Therefore, hit the below command in the terminal.
php spark migrate
This will generate the table along with its schema.
How to Send Email in CodeIgniter 4 Using Gmail SMTP
Create a Model in CodeIgniter 4 For Ajax Form Handling
In Codeigniter 4, you can create a model using the spark command. So, in the same terminal, hit the below command.
php spark make:model AjaxForm
The above command will generate a model file. Inside the created model, you will need to configure the table name as per the migration and also the allowed fields array. The allowed fields will accept the value for the defined fields inside the table.
<?php
namespace App\Models;
use CodeIgniter\Model;
class Ajaxform extends Model
{
protected $DBGroup = 'default';
protected $table = 'ajaxForms';
protected $primaryKey = 'id';
protected $useAutoIncrement = true;
protected $protectFields = true;
protected $allowedFields = ['name', 'email', 'password', 'address'];
// Dates
protected $useTimestamps = false;
protected $dateFormat = 'datetime';
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
}
That’s it for the model, and migration setup. Now, in the next step, you will require a view. The view will contain a basic form with some input fields.
Create a View in CodeIgniter 4 For Ajax Form Handling
For creating a view, come under the app/Views folder. Now, create a new file with the name ajax-form.php. Now, add the below snippet inside it.
<!doctype html>
<html lang="en">
<head>
<title>Codeigniter 4 Ajax Form Handling</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- bootstrap 5 CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.4.1/font/bootstrap-icons.css">
<style>
.error {
color: #dc3545;
}
</style>
</head>
<body>
<div class="container py-4">
<div class="row">
<div class="col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12 m-auto">
<form method="POST" action="javascript:void(0)" id="registrationForm">
<?= csrf_field() ?>
<div class="card shadow">
<div class="card-header">
<h5 class="card-title">Codeigniter 4 Ajax Form Handling</h5>
</div>
<div class="card-body p-4">
<div class="form-group mb-3 has-validation">
<label class="form-label" for="name">Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Name" value="<?php echo set_value('name'); ?>" />
</div>
<div class="form-group mb-3">
<label class="form-label" for="email">Email</label>
<input type="text" class="form-control" name="email" id="email" placeholder="Email" value="<?php echo set_value('email'); ?>" />
</div>
<div class="form-group mb-3">
<label class="form-label" for="password">Password</label>
<input type="password" class="form-control" id="password" name="password" placeholder="Password" value="<?php echo set_value('password'); ?>" />
</div>
<div class="form-group mb-3">
<label class="form-label" for="confirm_password">Confirm Password</label>
<input type="password" class="form-control" id="confirm_password" name="confirm_password" placeholder="Confirm Password" value="<?php echo set_value('confirm_password'); ?>" />
</div>
<div class="form-group mb-3">
<label class="form-label" for="phone">Phone</label>
<input type="text" class="form-control" id="phone" name="phone" placeholder="Phone" value="<?php echo set_value('phone'); ?>" />
</div>
<div class="form-group">
<label class="form-label" for="address">Address</label>
<textarea class="form-control" name="address" id="address" placeholder="Address"><?php echo set_value('address'); ?></textarea>
</div>
</div>
<div class="card-footer d-flex align-items-center">
<button type="submit" id="submit-btn" class="btn btn-success">Save</button>
<div class="response-message ms-3"></div>
</div>
</div>
</form>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></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>
<script>
if ($("#registrationForm").length > 0) {
$("#registrationForm").validate({
rules: {
name: {
required: true,
maxlength: 50
},
email: {
required: true,
maxlength: 50,
email: true,
},
password: {
required: true,
minlength: 5,
maxlength: 20,
},
confirm_password: {
required: true,
equalTo: "#password",
},
phone: {
required: true,
digits: true,
minlength: 10,
maxlength: 12,
},
address: {
required: true,
minlength: 10,
maxlength: 200,
},
},
messages: {
name: {
required: "Please enter your name",
maxlength: "Name length should be 50 characters long."
},
email: {
required: "Please enter your email",
maxlength: "Email length should be 50 characters long.",
email: "Please enter a valid email",
},
password: {
required: "Please enter your password",
minlength: "Password must be greater than 5 chars",
maxlength: "Password must not be greater than 20 chars",
},
confirm_password: {
required: "Please re-enter your password",
equalTo: "Password not confirmed",
},
phone: {
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",
},
address: {
required: "Please enter your address",
minlength: "Address must be greater than 10 chars",
maxlength: "Address must not be greater than 200 chars",
},
},
submitHandler: function(form) {
$('.response-message').removeClass('d-none');
$('#submit-btn').html('Sending..');
$.ajax({
url: "<?php echo base_url('ajax-store') ?>",
type: "POST",
data: $('#registrationForm').serialize(),
dataType: "json",
success: function(response) {
$('#submit-btn').html('Submit');
$('.response-message').html(response?.message);
response?.status === 'success' && $('.response-message').addClass('text-success') || $('.response-message').addClass('text-danger');
$('.response-message').show();
$('.response-message').removeClass('d-none');
document.getElementById("registrationForm").reset();
setTimeout(function() {
$('.response-message').hide();
}, 5000);
}
});
}
})
}
</script>
</body>
</html>
In the above code, I have added a very basic form. At the bottom, I’ve added jQuery to handle the form request. Also, the validation is there for the specified input fields. For the validation, I used the jQuery Validator plugin. This is used here to handle the validation with the form submit action. You can create a separate js file for this and you can add the script part in that. Then you can include that file inside this view file. That’s it in the above snippet.
Now, let’s come to the functionality part where we’ll handle the form request. Also, we will save the form data in our table through the model. Hence, let’s do that.
Generate Fake Data in CodeIgniter 4 Using Seeder and Faker
Create a Controller For Ajax Form Handling in CodeIgniter 4
Come back to the terminal, and create a controller using the spark command.
php spark make:controller AjaxController
After creating the controller, let’s put the below snippet inside it.
<?php
namespace App\Controllers;
use App\Controllers\BaseController;
use App\Models\Ajaxform;
class AjaxController extends BaseController
{
/**
* Constructor
*/
public function __construct()
{
helper(['form', 'url']);
$this->ajaxForm = new Ajaxform();
}
/**
* Show Ajax Form
* @param NA
* @return view
*/
public function index()
{
return view('ajax-form');
}
/**
* Ajax Form Store Data
* @param NA
* @return response
*/
public function store()
{
$data = [
'name' => $this->request->getVar('name'),
'email' => $this->request->getVar('email'),
'password' => $this->request->getVar('password'),
'phone' => $this->request->getVar('phone'),
'address' => $this->request->getVar('address'),
];
$result = $this->ajaxForm->save($data);
if ($result) {
return $this->response->setJSON(['status' => 'success', 'message' => 'User registered successfully']);
}
return $this->response->setJSON(['status' => 'failed', 'message' => 'Failed to register']);
}
}
Let me explain the above code before moving to the next step.
- At the top, I have included the Model (Ajaxform).
- Then we have the constructor. In the constructor function, I have included the CodeIgniter helper functions. Which are required for handling form data. Also, I have created the object of the model.
- Now, coming to the index() function. In this function, I have loaded the view in which we already created a baisc form.
- Lastly, we have the store() function that handles the form data and insert operation through the model object.
That’s it for the functionality we have. These functions needed a route to be run on the browser. So, let’s add the routes.
Create Routes in CodeIgniter 4
You can find the Routes.php under the app/Config directory of the project. Now, add the below routes.
$routes->get('ajax-form', 'AjaxController::index');
$routes->post('ajax-store', 'AjaxController::store');
Now, you are ready to go for the result.
Check Results of CodeIgniter AJAX Form Handling
Run the CodeIgniter 4 project using the spark command.
php spark serve
Now, come to the browser, hit the URL and you will have the below result.
If you will try to submit the form without filling up any fields then you will get validation errors.
Now, try to fill up the required fields and re-submit the form. As a result, you will get the success response as shown below. If the result is an error then the message will be displayed in red.
Conclusion
We used Ajax in CodeIgniter 4 for the form handling. The form is able to submit without refreshing the page. Also, we added the jQuery validation for the form. For submitting the form, we haven’t created any submit events additionally. Instead, we used the submit handler of the jQuery validator. I hope this will make sense for you.
Leave a Reply