Codeigniter - Upload image with preview using jQuery Ajax Form Plugin with example

Codeigniter - Upload image with preview using jQuery Ajax Form Plugin with example

In this PHP Codeigniter Tutorial, I will let you know how to upload image with preview using jQuery Form plugin with example.

jQuery Form plugin allows you to easily upload files or images on the server without refreshing the page.

jQuery Ajax request gives you ability to communicate with a server without reloading the entire web page.

Ok, let's start with few steps to upload image using ajax in codeigniter application :

Step1: Setup the fresh application

In this first step, download the updated version of Codeigniter 3 : Download CodeIgniter 3.x.

Step2: Add Routes

In this step, I will add following routes to work with request for ajax image upload.

application/config/routes.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');


$route['default_controller'] = 'welcome';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
$route['upload-image-using-ajax'] = 'ImageUpload';
$route['upload-image-using-ajax/post']['post'] = "ImageUpload/uploadImage";

?>
Step3: Add Controller

In this step, I will create a controller called "ImageUpload.php" in following path application/controllers/

<?php

class ImageUpload extends CI_Controller {


   public function __construct() { 
      
      parent::__construct(); 
      $this->load->helper(array('form', 'url')); 
   }

   public function index() { 
      $this->load->view('upload_image_form', array('error' => '' )); 
   } 


   /**
    * Method to upload image 
    *
    * @return Response
   */
   public function uploadImage() { 
      header('Content-Type: application/json');
      
      $config['upload_path']   = './images/'; 
      $config['allowed_types'] = 'gif|jpg|png|jpeg'; 
      $config['max_size']      = 2048;
      $this->load->library('upload', $config);
    
      if ( ! $this->upload->do_upload('file')) {
         $error = array('error' => $this->upload->display_errors()); 
         echo json_encode($error);
      }else { 
         $data = $this->upload->data();
         $success = ['success'=>$data['file_name']];
         echo json_encode($success);
      } 
   }
} 


?>

In Codeigniter, There is Upload class that provides a simple and easy way to upload files on the server.

Step4: Create View File

In this step, I will create a "upload_image_form.php" file in view directory.

There are number of libraries and helpers method in Codeigniter, so I am going to use form_open_multipart helper method to open a form tag, You can use this helper method when you are going to upload any files or documents.

form_open_multipart is same as form_open but form_open_multipart add an additional attribute called enctype="multipart/form-data".

<html>
  <head> 
      <title>Image Upload Example from Scratch</title>
      <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
      <script src="http://malsup.github.com/jquery.form.js"></script>
  </head>
  <body> 

      <?php echo form_open_multipart('upload-image-using-ajax/post');?> 
         <input type="file" name="file" size="20" />
         <input type="submit" class="btn-image-upload" value="upload" /> 
      </form> 
      <div class="preview" style="display: none;">
        <img src="">
      </div>

   <script type="text/javascript">
      $("body").on("click",".btn-image-upload",function(e){
       $(this).parents("form").ajaxForm(options);
      });


     var options = { 
       complete: function(response) 
       {
         if($.isEmptyObject(response.responseJSON.error)){
            alert('Image Upload Successfully.');
            $(".preview").css("display","block");
            $(".preview").find("img").attr("src","./images/"+response.responseJSON.success);
         }else{
            alert(response.responseJSON.error);
         }
       }
     };

   </script>
  </body>
</html>

Phone: (+91) 8800417876
Noida, 201301