Codeigniter 4 Ajax Image Upload With Preview Example

Codeigniter 4 Ajax Image Upload With Preview Example

Hello friends, Today we will show Codeigniter 4 Ajax Image Upload With Preview Example Tutorial. We will explain how to use ajax image upload with preview in codeigniter 4. In this example you will learn Codeigniter 4 Ajax Image Upload tutorial.

Here we will show how to step by step create image upload and preview functionality in Codeigniter 4 with the help of jQuery ajax from scratch. In this post you learn CodeIgniter 4 tutorial upload the image file using jquery ajax.

How to Upload Image using jQuery ajax in Codeigniter 4

Step 1: Download Fresh Codeigniter 4 for upload Image 

In step we will need to download fresh version of Codeigniter 4, so if you haven’t download yet then download from here : Download Codeigniter 4.

Step 2: Configurations

Next, we will set some configuration on the app/config/app.php file, so let’s go to application/config/config.php and open this file on text editor.

public $baseURL = 'http://localhost:8080';
public $baseURL = 'http://localhost/demo/';

Step 3: Create Database With Table

In this step, we required to create a database name demo, so let’s open your PHPMyAdmin and create the database with the name demo. After successfully create a database, you can use the below SQL query for creating a table in your database.

    id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
    name varchar(100) NOT NULL COMMENT 'Name',
    type varchar(255) NOT NULL COMMENT 'file type',
    created_at varchar(20) NOT NULL COMMENT 'Created date',
    PRIMARY KEY (id)

Step 4: Setup Database Credentials

Now, we required to connect our project to the database. we required to go app/Config/Database.php and open database.php file in text editor. After opening the file in a text editor, We required to set up database credentials in this file like follow.

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

Step 5: Create Controller for Codeigniter 4 Ajax Image Upload

In this step you Go to app/Controllers and create a controller name Form.php. In this controller, we will create some method/function. We will build some of the methods like :

namespace App\Controllers;
use CodeIgniter\Controller;
class Form extends Controller
    public function index()
         return view('form');
    public function store()
     helper(['form', 'url']);
     $db      = \Config\Database::connect();
         $builder = $db->table('file');
        $validated = $this->validate([
            'file' => [
        $response = [
            'success' => false,
            'data' => '',
            'msg' => "Image has not been uploaded successfully"
        if ($validated) {
            $avatar = $this->request->getFile('file');
            $avatar->move(WRITEPATH . 'uploads');
          $data = [
            'name' =>  $avatar->getClientName(),
            'type'  => $avatar->getClientMimeType()
           $save = $builder->insert($data);
           $response = [
            'success' => true,
            'data' => $save,
            'msg' => "Image has been uploaded successfully"
       return $this->response->setJSON($response);

Step 6: Create Views

Now we required to create form.php, go to application/views/ folder and create form.php file. and update the following HTML into your files:

<!DOCTYPE html>
  <title>Codeigniter 4 Ajax Image upload with preview Example</title>
 <link rel="stylesheet" href="">
<script src=""></script>
<style type="text/css">
  #blah {
  width: 600px;
  height: 300px;
  border: 2px solid;
  display: block;
  margin: 10px;
  background-color: white;
  border-radius: 5px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);
  transition: all 0.3s cubic-bezier(.25,.8,.25,1);
  overflow: hidden;
 <div  class="container">
   <div class="row">
   <form method="post" id="upload_form" enctype="multipart/form-data">  
     <div class="col-md-7">
       <h1> codeigniter 4 tutorial upload image file using jquery ajax </h1></br>
        <div id="divMsg" class="alert alert-success" style="display: none">
         <span id="msg"></span>
        <img id="blah" src="//" alt="your image" /></br></br>
        <input type="file" name="file" multiple="true" accept="image/*" id="finput" onchange="readURL(this);"></br></br>
        <button class="btn btn-success">Submit</button>
     <div class="col-md-5"></div>
  function readURL(input, id) {
    id = id || '#blah';
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
      $('#upload_form').on('submit', function(e){  
           if($('#file').val() == '')  
                alert("Please Select the File"); 
                     url:"<?php echo base_url(); ?>form/store",   
                     data:new FormData(this),  
                     contentType: false,  
                     cache: false,  
                     dataType: "json",
                        if(res.success == true){
                        else if(res.success == false){
                        }, 3000);

Step 7: Start Development server

For start development server, Go to the browser and hit following the URL.


I hope you understand of Codeigniter 4 Ajax Image Upload with Preview and it can help you…

Read Also :  CodeIgniter 4 Watermark Image Example