Using this Codeigniter 4 Ajax Form Submit Tutorial we’ll show you how to submit a form using ajax in Codeigniter to save the data without reload or refresh the page.
Here’s how to set up a simple form that uses AJAX to submit data to the server and store it in the database, utilizing jQuery for validation:
Step 1 – Setup CodeIgniter 4
Download CodeIgniter 4 from the official site. Unzip the downloaded file into the xampp/htdocs
directory. Then, modify the app/Config/App.php
file to set the base URL:
public $baseURL = 'http://localhost/your-project/public';
Step 2 – Create Database and Table
Create a database on your MySQL server, and set up a table named contacts
with the following SQL statement:
CREATE TABLE `contacts` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(100) NOT NULL,
`email` VARCHAR(100) NOT NULL,
`message` TEXT NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
Step 3 – Create the Model
Navigate to the app/Models
directory and create a model file named ContactModel.php
:
<?php
namespace App\Models;
use CodeIgniter\Model;
class ContactModel extends Model
{
protected $table = 'contacts';
protected $primaryKey = 'id';
protected $allowedFields = ['name', 'email', 'message'];
}
Step 4 – Design the Form
Create a view file named contact_form.php
in the app/Views
directory:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Contact Form</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h1>Contact Us</h1>
<form id="contactForm">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<br>
<label for="message">Message:</label>
<textarea id="message" name="message" required></textarea>
<br>
<button type="submit">Submit</button>
</form>
<div id="response"></div>
</body>
</html>
Step 5 – Integrate AJAX with the Form
Add AJAX functionality to the contact_form.php
file to submit the form data without refreshing the page:
<script>
$(document).ready(function() {
$('#contactForm').on('submit', function(event) {
event.preventDefault();
$.ajax({
url: '<?= base_url('contact/submit') ?>',
method: 'POST',
data: $(this).serialize(),
dataType: 'json',
success: function(response) {
$('#response').html('<p>' + response.message + '</p>');
},
error: function(xhr, status, error) {
$('#response').html('<p>An error occurred: ' + xhr.responseText + '</p>');
}
});
});
});
</script>
Step 6 – Create the Controller
In the app/Controllers
directory, create a controller file named Contact.php
and define methods for handling form submissions via AJAX:
<?php
namespace App\Controllers;
use App\Models\ContactModel;
use CodeIgniter\HTTP\ResponseInterface;
class Contact extends BaseController
{
public function index()
{
return view('contact_form');
}
public function submit()
{
$contactModel = new ContactModel();
$data = [
'name' => $this->request->getPost('name'),
'email' => $this->request->getPost('email'),
'message' => $this->request->getPost('message'),
];
if ($contactModel->insert($data)) {
return $this->response->setJSON(['status' => 'success', 'message' => 'Form submitted successfully.']);
} else {
return $this->response->setJSON(['status' => 'error', 'message' => 'Form submission failed.']);
}
}
}
Step 7 – Define Routes
Update the app/Config/Routes.php
file to include the routes for handling AJAX form submissions:
$routes->get('contact', 'Contact::index');
$routes->post('contact/submit', 'Contact::submit');
Step 8 – Test the Application
Navigate to your project directory and start the application server using the command:
cd /your-project
php spark serve
Then, open your browser and go to http://localhost:8080/contact
to test the form’s functionality.