CodeIgniter 4 Form Data Submit by Ajax Method

Share this Article

CodeIgniter 4 is a open source PHP Framework. Inside this article we will see about implementation of Ajax Request in CodeIgniter 4 Tutorial. Nowadays, every application somewhere uses Ajax request either for any operations like Create, Read, Update & Delete in CodeIgniter 4.

We will create a form with few input fields and try to upload in codeIgniter 4 using Ajax request.

Note*: For this article, CodeIgniter v4.1 setup has been installed. May be when you are seeing, version will be updated. CodeIgniter 4.x still is in development mode.

Let’s get started.


Download & Install CodeIgniter 4 Setup

We need to download & install CodeIgniter 4 application setup to system. To set application we have multiple options to proceed. Here are the following ways to download and install CodeIgniter 4 –

  • Manual Download
  • Composer Installation
  • Clone Github repository of CodeIgniter 4

Complete introduction of CodeIgniter 4 basics – Click here to go. After going through this article you can easily download & install setup.

Here is the command to install via composer –

$ composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.

Now, let’s configure database and application connectivity.


Settings Environment Variables

When we install CodeIgniter 4, we have env file at root. To use the environment variables means using variables at global scope we need to do env to .env

Open project in terminal

$ cp env .env

Above command will create a copy of env file to .env file. Now we are ready to use environment variables.

CodeIgniter starts up in production mode by default. Let’s do it in development mode. So that while working if we get any error then error will show up.

# CI_ENVIRONMENT = production

// Do it to 

CI_ENVIRONMENT = development

Now application is in development mode.


Create Database & Table in Application

We need to create a database. For database we will use MySQL. We have 2 options available to create database. Either we can use PhpMyAdmin Manual interface Or we can use command to create.

CREATE DATABASE codeigniter4_app;

Next, we need a table. That table will be responsible to store data. Let’s create table with some columns.

CREATE TABLE `tbl_users` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(120) DEFAULT NULL,
 `email` varchar(120) DEFAULT NULL,
 `mobile` varchar(45) DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Successfully, we have created a database and a table. Let’s connect with the application.


Database Connectivity to Application

Open .env file from project root. Search for DATABASE. You should see the connection environment variables.

Let’s set the value for those to connect with database.

 
#--------------------------------------------------------------------
# DATABASE
#-------------------------------------------------------------------- 
 database.default.hostname = localhost
 database.default.database = codeigniter4_app
 database.default.username = root
 database.default.password = root
 database.default.DBDriver = MySQLi
   

Now, database successfully connected with application.


Create Routes

To configure application routes, we need to open up the file /app/Config/Routes.php. This is the main routes config file where we will do all routes of application.

// Normal Controller
$routes->get("add-user", "User::addUser");

// Controller to handle Ajax Request
$routes->post("save-user", "Ajax::saveUser"); 

Here, we have configured our application.

Let’s create Model.


Set Application Model

Model is the face of application with the database. We need a Member Model which will do some basic model configuration.

Models are created at /app/Models. We are going to create UserModel.php at this location.

$ php spark make:model User --suffix

It will create UserModel.php at /app/Models folder.

<?php

namespace App\Models;

use CodeIgniter\Model;

class UserModel extends Model
{
	protected $DBGroup              = 'default';
	protected $table                = 'tbl_users';
	protected $primaryKey           = 'id';
	protected $useAutoIncrement     = true;
	protected $insertID             = 0;
	protected $returnType           = 'array';
	protected $useSoftDelete        = false;
	protected $protectFields        = true;
	protected $allowedFields        = [
		"name", 
		"email", 
		"mobile"
	];

	// Dates
	protected $useTimestamps        = false;
	protected $dateFormat           = 'datetime';
	protected $createdField         = 'created_at';
	protected $updatedField         = 'updated_at';
	protected $deletedField         = 'deleted_at';

	// Validation
	protected $validationRules      = [];
	protected $validationMessages   = [];
	protected $skipValidation       = false;
	protected $cleanValidationRules = true;

	// Callbacks
	protected $allowCallbacks       = true;
	protected $beforeInsert         = [];
	protected $afterInsert          = [];
	protected $beforeUpdate         = [];
	protected $afterUpdate          = [];
	protected $beforeFind           = [];
	protected $afterFind            = [];
	protected $beforeDelete         = [];
	protected $afterDelete          = [];
}

Application Controller Settings

Controller is the functional file. Firstly let’s load a helper at Parent Controller i.e BaseController.php. This file is in /app/Controllers folder.

Search helpers in BaseController and load “url” into helpers.

protected $helpers = [‘url’];

After loading this url helper, we will able to use site_url() and base_url() in Controllers & Views else we should have some error.

We will create application controller at /app/Controllers. Let’s create User.php & Ajax.php inside the given folder.

$ php spark make:controller User

$ php spark make:controller Ajax

Write the following code into /app/Controllers/User.php

<?php

namespace App\Controllers;

class User extends BaseController
{
    public function addUser()
    {
        helper(["url"]);
        // layout of add user form
        return view('add-user');
    }
}

Write the following code into /app/Controllers/Ajax.php

<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\UserModel;

class Ajax extends BaseController
{
    public function saveUser()
    {
        helper(["url"]);

        if ($this->request->getMethod() == "post") {

            $userModel = new UserModel();

            $data = [
                "name" => $this->request->getVar("name"),
                "email" => $this->request->getVar("email"),
                "mobile" => $this->request->getVar("mobile"),
            ];

            if ($userModel->insert($data)) {

                echo json_encode(array("status" => true, "message" => "User created"));
            } else {

                echo json_encode(array("status" => false, "message" => "Failed to create user"));
            }
        }
    }
}

View File Setup in Application

We need to create view file. View file for Add User. View files generally created inside /app/Views.

Let’s create it.

Add User view file. File with the name of add-user.php

Code of /app/Views/add-user.php

<form action="javascript:void(0)" id="frm-add-user" method="post">
    <p>
        Name: <input type="text" name="name" placeholder="Enter name" />
    </p>

    <p>
        Email: <input type="email" name="email" placeholder="Enter email" />
    </p>

    <p>
        Mobile: <input type="text" name="mobile" placeholder="Enter mobile" />
    </p>

    <p>
        <button type="submit">Submit</button>
    </p>
</form>

<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/jquery.validate.min.js"></script>

<script>
$(function() {
    $("#frm-add-user").validate({
        submitHandler: function() {
            var formdata = $('#frm-add-user').serialize();
            $.ajax({
                url: "<?= site_url('save-user') ?>",
                type: "POST",
                data: formdata,
                dataType: "JSON",
                success: function(data) {
                    console.log(data);
                    //location.reload();
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    alert('Error at add data');
                }
            });
        }
    });
});
</script>
  • $(“#frm-add-user”).validate({}); Using validate method validation library. As you can see inside view file code we have also added jquery.validate.min.js This is for client side form validation.
  • var formdata = $(‘#frm-add-user’).serialize(); Store form data in serialized format.
  • $.ajax({}); Using ajax method of jQuery. This method have some properties as you can see we have used in the ajax request configuration.

Testing Developed Application

Open project into terminal and start development server.

$ php spark serve

Back to browser and open up the project URL http://localhost:8080/add-user

When we open add user form at browser, we should see something like this –

Let’s fill some data and press submit button to initiate Ajax request and to save data into table.

Successfully, we have implemented Ajax Request in CodeIgniter 4. By Ajax request now we are saving our data.

We hope this article helped you to learn about CodeIgniter 4 Form Data Submit by Ajax Method in a very detailed way.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Find More on CodeIgniter 4 here

Leave a Comment