Codeigniter JQuery Ajax Image Upload Example

By Hardik Savani November 5, 2023 Category : PHP Bootstrap HTML jQuery Codeigniter Ajax

In this tutorial, I am going to explain how to upload image or file with jquery ajax using jquery form js in codeigniter application.

As we know we always require to create function for image or file upload in our web application. So we require to give possibility to image upload. Image Upload functionality is a very basic require to all most back-end project for like user profile picture upload, product image upload, category photo upload etc. If you want to give just image upload without ajax then you can also follow this link : How to upload image with validation in Codeigniter?, But it is better if you give more flexible to customer with ajax. So without page refresh image uploading in codeigniter project. You have to just follow few step to create example of image or file uploading with validation using jquery ajax.

So, just follow few step to make ajax image uploading example in codeigniter project. So let's follow:

Step 1: Download Fresh Codeigniter 3

In First step we will download fresh version of Codeigniter 3, so if you haven't download yet then download from here : Download Codeigniter 3.

Step 2: Add Route

In this step you have to add some route in your route file. So first we will create route for image uploading example.so put the bellow content in route file:

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['ajax-image-upload'] = 'AjaxImageUpload';

$route['ajax-image-upload/post']['post'] = "AjaxImageUpload/uploadImage";

Step 3: Create Controller

In this step, we have to create "AjaxImageUpload" controller with index() and uploadImage(). so create AjaxImageUpload.php file in this path application/controllers/AjaxImageUpload.php and put bellow code in this file:

application/controllers/AjaxImageUpload.php

<?php


class AjaxImageUpload extends CI_Controller {


/**

* Manage __construct

*

* @return Response

*/

public function __construct() {

parent::__construct();

$this->load->helper(array('form', 'url'));

}


/**

* Manage index

*

* @return Response

*/

public function index() {

$this->load->view('ajaxImageUploadForm', array('error' => '' ));

}


/**

* Manage uploadImage

*

* @return Response

*/

public function uploadImage() {

header('Content-Type: application/json');

$config['upload_path'] = './uploads/';

$config['allowed_types'] = 'gif|jpg|png';

$config['max_size'] = 1024;

$this->load->library('upload', $config);

if ( ! $this->upload->do_upload('image')) {

$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);

}

}

}


?>

Step 4: Create View

In this step we will create ajaxImageUploadForm.php view file . In this file we will write design of html form using form helper and url helper. We also write jquery ajax code on this file. So let's update following file:

application/views/ajaxImageUploadForm.php

<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('ajax-image-upload/post');?>

<input type="file" name="image" size="20" />

<input type="submit" class="upload-image" value="upload" />

</form>


<div class="preview" style="display: none;">

<img src="">

</div>


</body>


<script type="text/javascript">

$("body").on("click",".upload-image",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","/uploads/"+response.responseJSON.success);

}else{

alert('Image Upload Error.');

}

}

};


</script>


</html>

Ok Now we are ready to run Above example, But We have to create "uploads" folder on your root directory before run example. all images will upload on "uploads" directory so make sure permission too.

So let's run bellow command on your root directory for quick run:

php -S localhost:8000

Now you can open bellow URL on your browser:

http://localhost:8000/ajax-image-upload

Make Sure, First you have to set base URL on your bellow configuration file :

application/config/config.php

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

I hope it can help you...

Shares