If you are searching like, CodeIgniter 4 tutorial upload image file using jquery ajax, ajax image upload in CodeIgniter, CodeIgniter image upload with preview, ajax form submit with file upload in CodeIgniter. So this tutorial is very helpful for you.
In this tutorial, you will learn how to use jQuery Ajax to upload images in the Codeigniter 4 project with preview. Also, how can you upload images from jQuery Ajax without refreshing and reloading the whole web page of your CodeIgniter 4 application.
Codeigniter 4 jQuery Ajax Image Upload with Preview Tutorial Example
Follow the below steps and easily upload the image using jQuery ajax in folder and store into the database in CodeIgniter 4 projects with preview:
- Step 1: Setup Codeigniter Project
- Step 2: Basic Configurations
- Step 3: Create Database With Table
- Step 4: Setup Database Credentials
- Step 5: Create Controller
- Step 6: Create Views
- Step 7: Start Development server
Step 1: Setup Codeigniter Project
In this step, we will download the latest version of Codeigniter 4, Go to this link https://codeigniter.com/download Download Codeigniter 4 fresh new setup and unzip the setup in your local system xampp/htdocs/ . And change the download folder name “demo”
Step 2: Basic Configurations
Next, we will set some basic configuration on the app/config/app.php file, so let’s go to application/config/config.php and open this file on text editor.
Set Base URL like this
public $baseURL = 'http://localhost:8080'; To public $baseURL = 'http://localhost/demo/';
Step 3: Create Database With Table
In this step, we need 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
In this step, we need to connect our project to the database. we need to go app/Config/Database.php and open database.php file in text editor. After opening the file in a text editor, We need to set up database credentials in this file like below.
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
Now 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 :
- Index() – This is used to display file/image upload form.
- Store() – This is used to validate form file/image on server-side and store into MySQL database and folder.
<?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 need 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>
This below line display error messages on your web page:
<div id="divMsg" class="alert alert-success" style="display: none"> <span id="msg"></span> </div>
This below javascript code show preview of your image before upload to server in codeigniter 4 projects:
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]); } }
The below given ajax code is used to upload image into the server in codeigniter 4 projects. So include this code into your web page:
$(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(); ?>public/index.php/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(); } }); } }); });
Step 7: Start Development server
For start development server, Go to the browser and hit below the URL.
http://localhost/demo/public/index.php/form
Conclusion
In this Codeigniter 4 ajax image upload with preview example tutorial. You have learned how to upload image in CodeIgniter 4 projects using jQuery ajax with preview.
Recommended Codeigniter Posts
If you have any questions or thoughts to share, use the comment form below to reach us.