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';
To
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.

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

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 :

<?php 
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' => [
                'uploaded[file]',
                'mime_in[file,image/jpg,image/jpeg,image/gif,image/png]',
                'max_size[file,4096]',
            ],
        ]);
 
        $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>
<html>
<head>
  <title>Codeigniter 4 Ajax Image upload with preview Example</title>
</head>
 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></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;
}
</style>
<body>
 <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>
        </div>
 
        <img id="blah" src="//www.tutsmake.com/ajax-image-upload-with-preview-in-codeigniter/" 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>
 
     <div class="col-md-5"></div>
 
   </form>
   </div>
 </div>
<script>
  function readURL(input, id) {
    id = id || '#blah';
    if (input.files && input.files[0]) {
        var reader = new FileReader();
 
        reader.onload = function (e) {
            $(id)
                    .attr('src', e.target.result)
                    .width(200)
                    .height(150);
        };
 
        reader.readAsDataURL(input.files[0]);
    }
 }
 $(document).ready(function(){  
      $('#upload_form').on('submit', function(e){  
 
           $('.btn-success').html('sending');
           $('.btn-success').prop('disabled');
 
           e.preventDefault();  
           if($('#file').val() == '')  
           {  
                alert("Please Select the File"); 
                $('.btn-success').html('submit');
                $('.btn-success').prop('enabled'); 
                document.getElementById("upload_form").reset(); 
           }  
           else  
           {  
              $.ajax({  
                     url:"<?php echo base_url(); ?>form/store",   
                     method:"POST",  
                     data:new FormData(this),  
                     contentType: false,  
                     cache: false,  
                     processData:false,  
                     dataType: "json",
                     success:function(res)  
                     {  
                        console.log(res.success);
                        if(res.success == true){
                         $('#blah').attr('src','//www.tutsmake.com/ajax-image-upload-with-preview-in-codeigniter/');   
                         $('#msg').html(res.msg);   
                         $('#divMsg').show();   
                        }
                        else if(res.success == false){
                          $('#msg').html(res.msg); 
                          $('#divMsg').show(); 
                        }
                        setTimeout(function(){
                         $('#msg').html('');
                         $('#divMsg').hide(); 
                        }, 3000);
 
                      $('.btn-success').html('submit');
                      $('.btn-success').prop('enabled');
                       document.getElementById("upload_form").reset(); 
                     }  
              });  
           }  
      });  
 }); 
</script>  
</body>
</html>

Step 7: Start Development server

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

http://localhost/demo/public/index.php/form

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

Read Also :  Delete Data in CodeIgniter Example