Codeigniter JQuery Ajax Image File Upload Tutorial

Codeigniter JQuery Ajax Image File Upload Tutorial

In this tutorial guide, we will share how to upload an image to a database and folder using jQuery Ajax and how to display a preview of the image before uploading and without refreshing and reloading the page in CodeIgniter projects.

How to Upload Image File using Codeigniter and Ajax

Here are steps for that:

  • Download Codeigniter Latest
  • Basic Configurations
  • Create Database With Table
  • Setup Database Credentials
  • Make New Controller
  • Create Views
  • Start Development server
  • Conclusion

Download Codeigniter Project

In this step we will download the latest version of Codeigniter, Go to this link Download Codeigniter. Download the fresh setup of codeigniter and unzip the setup in your local system xampp/htdocs/ and also rename your project folder name to demo.

Basic Configurations

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

Set Base URL like this

$config['base_url'] = 'http://localhost/demo';

Create Database With Table

In this step, we need to create 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 IF NOT EXISTS images(
id int(10) unsigned NOT NULL AUTO_INCREMENT,
name varchar(255) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=16 ;

Setup Database Credentials

Edit database.php file from application/config/ folder and add the database details like the following:

$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'demo',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);

Create Controller

Create controller name Ajax.php in application/controllers folder that handle image upload process in it.

<?php
class Ajax extends CI_Controller {

public function __construct()
{
parent::__construct();
$this->load->helper('form');
$this->load->database();
}
public function image()
{
$this->load->view('image');
}
function ajaxImageStore()
{
if(isset($_FILES["image_file"]["name"]))
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$this->load->library('upload', $config);
if(!$this->upload->do_upload('image_file'))
{
$error = $this->upload->display_errors();
echo json_encode(array('msg' => $error, 'success' => false));
}
else
{
$data = $this->upload->data();
$insert['name'] = $data['file_name'];
$this->db->insert('images',$insert);
$getId = $this->db->insert_id();
$arr = array('msg' => 'Image has not uploaded successfully', 'success' => false);
if($getId){
$arr = array('msg' => 'Image has been uploaded successfully', 'success' => true);
}
echo json_encode($arr);
}
}
}

}

Create Views

Create view for showing image upload form in application/views/ that allow users to choose image file for upload:

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/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> Upload & Display Image</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="image_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>
</body>
</html>

Implement jQuery ajax code to handle preview of image and upload process:

<script type="text/javascript">
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah')
.attr('src', e.target.result);
};
reader.readAsDataURL(input.files[0]);
}
}
$(document).ready(function(){
$('#upload_form').on('submit', function(e){
e.preventDefault();
if($('#image_file').val() == '')
{
alert("Please Select the File");
}
else
{
$.ajax({
url:"<?php echo base_url(); ?>ajax/ajaxImageStore",
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);
}
});
}
});
});
</script>

Test Project

Test project on browser:

http://localhost/demo/ajax/image

Conclusion

In this codeigniter ajax image tutorial – We have created a form for showing and uploading a image into database and folder.,

If you have any questions or thoughts to share, use the comment form below to reach us.

AuthorAdmin

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.

3 replies to Codeigniter JQuery Ajax Image File Upload Tutorial

  1. thanks for the tutorial. It’s very helpful for me

  2. Nice post….very usefull…happy coding..

  3. thanks Sir

Leave a Reply

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