Code your dreams into reality.
Every line of code is a step towards a better future.
Embrace the bugs, they make you a better debugger.

CodeIgniter 4 Ajax Form Submit Tutorial

Last Updated on July 11, 2024 by

AJAX allows developers to send form data to the server to store the data in the database and it returns the response in json format without refreshing the web page.

Let’s start by creating a simple form and send the form data to the server to be stored in the database using AJAX with jQuery validation:

Step 1 – Set up CodeIgniter 4

To download CodeIgniter 4 from the official website, Link:

Extract downloaded zip file in xampp/htdocs directory. and edit app/Config/App.php file, and set up base url in it:

public $baseURL = 'http://localhost/your-project/public';

Step 2 – Create a Database and Table

Create a database in your MySQL server for the project, and create a table named contacts by using the following sql query:

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

Go to app/Models directory and create a new file named ContactModel.php file:

namespace App\Models;

use CodeIgniter\Model;

class ContactModel extends Model
{
    protected $table = 'contacts';
    protected $primaryKey = 'id';
    protected $allowedFields = ['name', 'email', 'message'];
}

Step 4 – Create Form

Create a view file named contact_form.php in 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 – 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 – Create Controller Class

Go to app/controllers directory, and create a controller file named Contact.php, and create methods in it to handle form submission using ajax on server:

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 – Define Routes

Edit app/Config/Routes.php and define the routes to handle form submission using ajax requests:

$routes->get('contact', 'Contact::index');
$routes->post('contact/submit', 'Contact::submit');

Step 8 – Test Application

Run the following command to start application server:

cd /your-project
php spark serve

Open your browser and type to http://localhost:8080/contact url in it to test this application.

Leave a Comment