I am new in ajax. I am trying to make a file uploader with ajax in codeigniter. When I upload the file file is uploaded successfully in /uploads folder but response message that is alert or the image view is not working. I have searched several answers of same problem but could not solve it. Please help me to find the problem of code.
The controller :
<?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'] = 10240;
$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);
}
}
}
?>
The view file:
<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>
</html>
The ajax :
$("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.');
}
}
};`
if ($.isEmptyObject(response.responseJSON.success)) {
alert('Image Upload Successfully.');
$(".preview").css("display", "block");
$(".preview").find("img").attr("src", "/uploads/" + response.responseJSON.success);
} else {
alert('Image Upload Error.');
}