Codeigniter 4 jQuery Ajax Image Upload with Preview Tutorial

To create a CodeIgniter 4 application with jQuery AJAX image uploads and previews, you’ll need to set up your project, create the necessary HTML, JavaScript, and PHP code, and configure routes.

Steps for showing preview of image using jquery ajax:

Step 1: Setup Codeigniter 4 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: Implement CodeIgniter Controller

Create a controller method to handle the AJAX request and process the image upload.

Go to app/Controllers and create a controller name Form.php. In this controller, and will create some method in it.

<?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 HTML Form

Design an HTML form with an input field for uploading images and a preview area for displaying the selected image.

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: Write jQuery AJAX Function

Write JavaScript code using jQuery to handle the AJAX request for uploading the image with preview.

 $(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 8: Test Project

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.

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *