Codeigniter 4 Ajax Image Upload with Preview Example

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

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

In this Codeigniter ajax image upload with preview tutorial, iwill explain how to create image upload , preview function in Codeigniter with the help of jQuery from scratch.

Codeigniter 4 Ajax Image Upload and Image Preview Example

  • Step 1: Install Codeigniter App
  • Step 2: Enable The 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 Codeigniter app either you can install composer on your system and run the below command.

composer create-project codeigniter4/appstarter
Bash

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

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

Enable Error Debugging

You need to go to 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');
PHP

Create Table Using SQL

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

CREATE TABLE users (
    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)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='user table' AUTO_INCREMENT=1;
SQL

Add Database Details

In app/Config/Database.php file look for $default public variable,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,
    ];
PHP

CodeIgniter\Database\Exceptions\DatabaseException

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

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

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

Create AJAX Image Upload Controller

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

<?php 
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' => [
                'uploaded[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);
    }
}
PHP

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

Create Route

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

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

Set Up File Upload View

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

<!DOCTYPE html>
<html lang="en">
<head>
	<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="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
      .container { max-width: 750px }
    </style>
</head>

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

            <div class="d-grid text-center">
               <img class="mb-3" id="ajaxImgUpload" alt="Preview Image" src="https://via.placeholder.com/300" />
            </div>

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

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

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        function onFileUpload(input, id) {
            id = id || '#ajaxImgUpload';
            if (input.files && input.files[0]) {
                var reader = new FileReader();

                reader.onload = function (e) {
                    $(id).attr('src', e.target.result).width(300)
                };

                reader.readAsDataURL(input.files[0]);
            }
        }
        $(document).ready(function () {
            $('#upload_image_form').on('submit', function (e) {

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

                e.preventDefault();
                if ($('#file').val() == '') {
                    alert("Choose File");
                    $('.uploadBtn').html('Upload');
                    $('.uploadBtn').prop('enabled');
                    document.getElementById("upload_image_form").reset();
                } else {
                    $.ajax({
                        url: "<?php echo base_url(); ?>/AjaxFileUpload/upload",
                        method: "POST",
                        data: new FormData(this),
                        processData: false,
                        contentType: false,
                        cache: false,
                        dataType: "json",
                        success: function (res) {
                            console.log(res.success);
                            if (res.success == true) {
                                $('#ajaxImgUpload').attr('src', 'https://via.placeholder.com/300');
                                $('#alertMsg').html(res.msg);
                                $('#alertMessage').show();
                            } else if (res.success == false) {
                                $('#alertMsg').html(res.msg);
                                $('#alertMessage').show();
                            }
                            setTimeout(function () {
                                $('#alertMsg').html('');
                                $('#alertMessage').hide();
                            }, 4000);

                            $('.uploadBtn').html('Upload');
                            $('.uploadBtn').prop('Enabled');
                            document.getElementById("upload_image_form").reset();
                        }
                    });
                }
            });
        });
    </script>
</body>

</html>
PHP

Run Codeigniter Project

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

php spark serve
Bash

Here is url that helps you upload the file.

http://localhost:8080
Markup

Codeigniter Ajax Image Upload

Conclusion

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

Post a Comment

Previous Post Next Post