Using Codeigniter 4 Ajax Form Submit Tutorial you will learn how to submit form using Ajax in Codeigniter 4. AJAX empowers developers to seamlessly transmit form data to servers for database storage, delivering responses in JSON format without necessitating webpage refreshes.
Step 1: Setting Up CodeIgniter 4
Begin by downloading CodeIgniter 4 from the official website and extracting it into your xampp/htdocs
directory. Configure the baseURL
in app/Config/App.php
to match your local environment:
public $baseURL = 'http://localhost/your-project/public';
Step 2: Creating a MySQL Database and Table
Set up a MySQL database for your project and execute the following SQL query to create a contacts
table:
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: Developing the Model
Navigate to app/Models
and create 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: Designing the Contact Form
Create contact_form.php
in app/Views
:
<!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>
<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>
</body>
</html>
Step 5: Add Ajax in Form
Add ajax code to send data from form to server without refresh web page in contact_form.php
file:
<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: Implementing the Controller Logic
Create Contact.php
in app/Controllers
:
namespace App\Controllers;
use App\Models\ContactModel;
use CodeIgniter\HTTP\Response;
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' => 'Failed to submit form.']);
}
}
}
Step 7: Defining Routes
Configure routes in app/Config/Routes.php
to handle AJAX form submissions:
$routes->get('contact', 'Contact::index');
$routes->post('contact/submit', 'Contact::submit');
Step 8: Testing Your Application
Launch the application server with:
cd /your-project
php spark serve
Visit http://localhost:8080/contact
in your browser to begin testing your AJAX-enabled contact form.