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 post we will give you information about Codeigniter – Upload image with preview using jQuery Ajax Form Plugin with example. Hear we will give you detail about Codeigniter – Upload image with preview using jQuery Ajax Form Plugin with exampleAnd how to use it also give you demo for it if it is necessary.

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.

See also  Printing with Ionic 5, Ionic Native 5 and Cordova


application/config/routes.php

<?php
defined('BASEPATH') ORexit('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

classImageUploadextends CI_Controller {


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

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


   /**
    * Method to upload image 
    *
    * @return Response
   */
   publicfunctionuploadImage() { 
      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()); 
         echojson_encode($error);
      }else { 
         $data=$this->upload->data();
         $success= ['success'=>$data['file_name']];
         echojson_encode($success);
      } 
   }
} 


?>

See also  Laravel hasManyThrough eloquent relationship tutorial example - onlinecode

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> 

      <?phpecho form_open_multipart('upload-image-using-ajax/post');?> 
         <inputtype="file"name="file"size="20"/>
         <inputtype="submit"class="btn-image-upload"value="upload"/> 
      </form> 
      <divclass="preview"style="display: none;">
        <imgsrc="">
      </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>

See also  How to create a Resourceful Routing in Laravel 5.2

Try this..

Hope this code and post will helped you for implement Codeigniter – Upload image with preview using jQuery Ajax Form Plugin with example. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

Leave a Comment

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

  +  56  =  57

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US