CodeIgniter 4 Upload Image using Ajax Method

Share this Article

CodeIgniter 4 is a open source PHP Framework. Inside this article we will cover CodeIgniter 4 Upload Image with Form data using Ajax Request Tutorial. Nowadays, every application somewhere uses Ajax request either for any database operations. It’s common feature now.

We need to create a form with input type file and see the functions step by step to upload by using Ajax Request. Already we have article over form data upload by using Ajax, Click here to learn.

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.

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_students (
name varchar(120) DEFAULT NULL,
email varchar(120) DEFAULT NULL,
mobile varchar(45) DEFAULT NULL,
profile_image varchar(150) DEFAULT NULL,

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.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.

Application Routes Configuration

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-student", "Student::addStudent");

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

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 Student Model which will do some basic model configuration.

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

$ php spark make:model Student --suffix

namespace App\Models;

use CodeIgniter\Model;

class StudentModel extends Model
	protected $DBGroup              = 'default';
	protected $table                = 'tbl_students';
	protected $primaryKey           = 'id';
	protected $useAutoIncrement     = true;
	protected $insertID             = 0;
	protected $returnType           = 'array';
	protected $useSoftDelete        = false;
	protected $protectFields        = true;
	protected $allowedFields        = [

	// 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 some helpers 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 Student.php & Ajax.php inside the given folder.

$ php spark make:controller Student

$ php spark make:controller Ajax

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


namespace App\Controllers;

class Student extends BaseController
    public function addStudent()
        // layout of add student form
        return view('add-student');
  • Loading helper([“url”]); “url” helper in controller method
  • Calling view file return view(‘add-student’);

Write the following code into /app/Controllers/Ajax.php. Must See the commented lines in code to get more clear idea about file upload.


namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\StudentModel;

class Ajax extends BaseController
    public function saveStudent()

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

            $rules = [
                "name" => "required",
                "email" => "required|valid_email",
                "mobile" => "required",
                "profile_image" => [
                    "rules" => "uploaded[profile_image]|max_size[profile_image,1024]|is_image[profile_image]|mime_in[profile_image,image/jpg,image/jpeg,image/gif,image/png]",
                    "label" => "Profile Image",

            if (!$this->validate($rules)) {

                $response = [
                    'success' => false,
                    'msg' => "There are some validation errors",

                return $this->response->setJSON($response);
            } else {

                $file = $this->request->getFile('profile_image');
                $profile_image = $file->getName();
                /* UPLOAD IMAGE FILE IN /public folder */
                // If we want to upload image inside /public
                // create a folder with any name like "images"
                // $file->move("images"); This way move method automatically place 
                // the default name of the file to images folder inside /public folder.
                /* UPLOAD IMAGE FILE IN /writable folder */
                // Create /images folder inside /writable folder
                if ($file->move(WRITEPATH . "images", $profile_image)) {

                    $studentModel = new StudentModel();

                    $data = [
                        "name" => $this->request->getVar("name"),
                        "email" => $this->request->getVar("email"),
                        "mobile" => $this->request->getVar("mobile"),
                        "profile_image" => "images/" . $profile_image,

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

                        $response = [
                            'success' => true,
                            'msg' => "Student created successfully",
                    } else {

                        $response = [
                            'success' => false,
                            'msg' => "Failed to create student",

                    return $this->response->setJSON($response);
                } else {

                    $response = [
                        'success' => false,
                        'msg' => "Failed to upload Image",

                    return $this->response->setJSON($response);
  • if ($this->request->getMethod() == “post”) {} Checking request type
  • $rules = []; Defining input field validation rules
  • if (!$this->validate($rules)) {} Validating form values with validation rules
  • $file = $this->request->getFile(‘profile_image’); Reading file from submitted form data
  • if ($file->move(WRITEPATH . “images”, $profile_image)) {} Create images folder inside /writable folder. Stroing images inside that folder
  • if ($studentModel->insert($data)) {} Saving form data to database table.
  • return $this->response->setJSON($response); Sending response in JSON format

View File Setup in Application

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

Let’s create it.

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

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

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

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

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

        Mobile: <input type="file" name="profile_image" id="profile_image" onchange="readImageData(this);"/>

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

<script src=""></script>


function readImageData(input, id) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {


$(function() {

    $('#frm-add-student').on('submit', function(e){

                url: "<?=site_url('save-student')?>",
                type: "POST",
                data:new FormData(this),
                contentType: false,
                cache: false,
                dataType: "JSON",
                success: function(data) {
                error: function(jqXHR, textStatus, errorThrown) {
                    alert('Error at add data');
  • readImageData() This is a javascript developed function. Using this method every time when we upload any file then it will read binary data of image.
  • $(‘#frm-add-student’).on(‘submit’, function(e){}) This code is going to submit formdata to server
  • $.ajax({}); Using Ajax Method of jquery.
  • data:new FormData(this), Sending form data to server.

Testing Application

Open project in terminal and start development server.

$ php spark serve

Open up the application into browser.

URL: http://localhost:8080/add-student.

When we fill all needed data with file upload and clicked on submitted button.

We hope this article helped you to learn CodeIgniter 4 Upload Image Using Ajax Request 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