Codeigniter 4 Ajax Image Upload with Preview Example

Last updated on: by Editorial Team

Codeigniter 4 Ajax Image Upload and Preview tutorial; Uploading files and images is a common practice nowadays, bet it Facebook, Instagram, Twitter or any other website.

But do you know how to create this common feature of uploading an image and display the image preview in the Codeigniter 4 application using the jQuery AJAX (Asynchronous JavaScript and XML)?

In this Codeigniter ajax image upload with preview tutorial, we will explain how to step by step create image upload and preview functionality in Codeigniter with the help of jQuery ajax from scratch.

Codeigniter 4 Ajax Image Upload and Image Preview Example

  • Step 1: Install Codeigniter App
  • Step 2: Enable Error Debugging
  • Step 3: Create Database and Table
  • Step 4: Add Database Details
  • Step 5: Create AJAX Image Upload Controller
  • Step 6: Create Route
  • Step 7: Set Up File Upload View
  • Step 8: Run Codeigniter Project

Install Codeigniter App

There are two ways to create a new Codeigniter app either you can install composer on your system and run the following command.

composer create-project codeigniter4/appstarter

Make sure to rename the application name as per your choice.

Or, you can directly visit the Codeigniter website and download the latest version of the Codeigniter 4 app.

Enable Error Debugging

You need to get to the app/Config/Boot/development.php and app/Config/Boot/production.php file and change the display_errors property to 1 from 0.

ini_set('display_errors', '1');

Create Table Using SQL

In this section, we need to understand how to create a new table for file upload using the SQL query. We assume you have already created the database. Run the following command in the SQL tab of PHPMyAdmin to create a new table into the database.

    id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
    img_name varchar(100) NOT NULL COMMENT 'Image Name',
    file varchar(255) NOT NULL COMMENT 'File Type',
    created_at varchar(20) NOT NULL COMMENT 'Date Created',
    PRIMARY KEY (id)

Add Database Details

In the app/Config/Database.php file, look for $default public variable, and there you need to add the database name, user name and password.

public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'root',
        'password' => '',
        'database' => 'codeigniter_db',
        'DBDriver' => 'MySQLi',
        'DBPrefix' => '',
        'pConnect' => false,
        'DBDebug'  => (ENVIRONMENT !== 'development'),
        'cacheOn'  => false,
        'cacheDir' => '',
        'charset'  => 'utf8',
        'DBCollat' => 'utf8_general_ci',
        'swapPre'  => '',
        'encrypt'  => false,
        'compress' => false,
        'strictOn' => false,
        'failover' => [],
        'port'     => 3306,


There are a high chance that you might get Unable to connect database : Codeigniter the error, especially if you are working with MAMP or XAMP servers. You can define either of the hostname for MAMP or XAMP.

public $default = [
  'hostname' => '/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock',

public $default = [
  'hostname' => '/Applications/MAMP/tmp/mysql/mysql.sock',

Create AJAX Image Upload Controller

In the next step, you have to create a new controller file inside the app/Controllers folder; there, after open the app/Controllers/AjaxFileUpload.php file and update the given below code.

namespace App\Controllers;
use CodeIgniter\Controller;
class AjaxFileUpload extends Controller
    public function index()
         return view('index');
    public function upload()
        helper(['form', 'url']);
        $database = \Config\Database::connect();
        $builder = $database->table('users');

        $validateImage = $this->validate([
            'file' => [
                'mime_in[file, image/png, image/jpg,image/jpeg, image/gif]',
                'max_size[file, 4096]',
        $response = [
            'success' => false,
            'data' => '',
            'msg' => "Image could not upload"

        if ($validateImage) {
            $imageFile = $this->request->getFile('file');
            $imageFile->move(WRITEPATH . 'uploads');

            $data = [
                'img_name' => $imageFile->getClientName(),
                'file'  => $imageFile->getClientMimeType()

            $save = $builder->insert($data);

            $response = [
                'success' => true,
                'data' => $save,
                'msg' => "Image successfully uploaded"

        return $this->response->setJSON($response);

The index() function returns the view() method pass the view template name inside the method. Secondly, the upload() method validate the image, with mime type, file size and store the file into the database.

Create Route

Furthermore, open the app/Config/Routes.php file and define the route that will allow you to open the CI app on the browser.

$routes->get('/', 'AjaxFileUpload::index');

Set Up File Upload View

Next, head over to app/Views/ folder inside here create the index.php file and update the following code inside the app/Views/index.php file.

<!DOCTYPE html>
<html lang="en">
	<meta charset="UTF-8">
	<title>Codeigniter 4 Ajax Image upload and Preview Demo</title>
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="" rel="stylesheet">
      .container { max-width: 750px }

    <div class="container mt-5">
        <form method="post" id="upload_image_form" enctype="multipart/form-data">

            <div id="alertMessage" class="alert alert-warning mb-3" style="display: none">
                <span id="alertMsg"></span>

            <div class="d-grid text-center">
               <img class="mb-3" id="ajaxImgUpload" alt="Preview Image" src="" />

            <div class="mb-3">
                <input type="file" name="file" multiple="true" id="finput" onchange="onFileUpload(this);"
                    class="form-control form-control-lg"  accept="image/*">

            <div class="d-grid">
               <button type="submit" class="btn btn-danger uploadBtn">Upload</button>

    <script src=""></script>
        function onFileUpload(input, id) {
            id = id || '#ajaxImgUpload';
            if (input.files && input.files[0]) {
                var reader = new FileReader();

                reader.onload = function (e) {

        $(document).ready(function () {
            $('#upload_image_form').on('submit', function (e) {

                $('.uploadBtn').html('Uploading ...');

                if ($('#file').val() == '') {
                    alert("Choose File");
                } else {
                        url: "<?php echo base_url(); ?>/AjaxFileUpload/upload",
                        method: "POST",
                        data: new FormData(this),
                        processData: false,
                        contentType: false,
                        cache: false,
                        dataType: "json",
                        success: function (res) {
                            if (res.success == true) {
                                $('#ajaxImgUpload').attr('src', '');
                            } else if (res.success == false) {
                            setTimeout(function () {
                            }, 4000);



Run Codeigniter Project

In the final segment of this guide, we have to start the CI development server, and this can be done by executing the below command.

php spark serve

Here is the url that helps you upload the file.


Codeigniter Ajax Image Upload


Codeigniter 4 AJAX image uploading tutorial is over; AJAX comes up with many quintessential features that enhance the user experience in web applications. It is superb for asynchronous processing, lowers server hits and network load, and most importantly, gives swift page rendering with enhanced response times.