Upload Image/File Into Database Ajax Codeigniter

Codeigniter 3 Ajax Image Upload – We will share with how to upload image using ajax into database & folder. We will upload the image using ajax and jquery. We will upload the image using jquery ajax without page refresh and reload.

In this codeigniter ajax image upload tutorial with live preview. We will upload image into database and folder. Before upload image in database and folder we will show preview of the image.

In every web development, we need to upload image into database without refreshing and reloading the whole web page. In this codeigniter tutorial you will learn simple ajax image upload step by step.

Codeigniter Ajax Image Upload

Contents

  • 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

$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

Now we need to create a controller name Ajax.php. In this controller we will create some method/function name image() and ajaxImageStore() for showing and storing a image into database and folder.

Note:- Before upload a image go to your project root directory and create a folder name uploads where we will store a image.

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

Now we need to create view for showing image upload form, so go to application/views/ and here create one view name image.php. After create this view put the below html in view.

<!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 &amp; Display Image</h1></br>
        <div id="divMsg" class="alert alert-success" style="display: none">
         <span id="msg"></span>
        </div>
        <img id="blah" src="http://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>

After create a image.php file and put the above html, Next we need to put the ajax image sending code to the above file so put the below code in image.php file after closing a body tag.

<script type="text/javascript">
 function readURL(input) {
      if (input.files &amp;&amp; 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','http://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>

Start Development server

For start development server, Go to the browser and hit below the url.

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.

2 Comments

  1. panchhi said:

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

    August 7, 2019
    Reply
  2. Vale Rozi said:

    Nice post….very usefull…happy coding..

    August 25, 2019
    Reply

Leave a Reply

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