We will learn how to upload image or file with jquery ajax using jquery form js in codeigniter application.
Step 1:
Download Fresh Codeigniter 3: Download Codeigniter 3
Step 2:
Add Route 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 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 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>
Now you can run this example.