How can i upload image with ajax in codeigniter?
ajax, codeigniter, jquery, php
Solution
You can to use FormData api in html5.
Your form must be:
<form enctype="multipart/form-data" accept-charset="utf-8" name="formname" id="formname" method="post" action="">
Then jquery:
function uploadImage() {
if (typeof FormData !== 'undefined') {
// send the formData
var formData = new FormData( $("#formID")[0] );
$.ajax({
url : baseUrl + 'uploadImage', // Controller URL
type : 'POST',
data : formData,
async : false,
cache : false,
contentType : false,
processData : false,
success : function(data) {
successFunction(data);
}
});
} else {
message("Your Browser Don't support FormData API! Use IE 10 or Above!");
}
}
Then in the controller you will get the files in `$_FILES` array.
Problem
I'm trying to upload image with jQuery and ajax function, and how can I fetch all details of image file, like in php we use `$_FILE()` Here is my code JS ``` $("#uploadimg" ).click(function() { $( "#file" ).click(); }); $( "#file" ).change(function(e) { var file=$('#file').val(); alert(file); die(); e.preventDefault(); $.ajax({ url:'http://localhost/JSG/blog/uploadimg', secureuri:false, type: "POST", fileElementId:'image', dataType: 'text', data:{ file: file }, cache: true, success: function (data){ alert(data); console.log(data); }, }); }); ``` Controller ``` public function uploadimg() { $var = $_POST['file']; print_r($var); if($this->input->post('file')) { $config['upload_path'] = 'upload'; $config['file_name'] = $var; $config['overwrite'] = 'TRUE'; $config["allowed_types"] = 'jpg|jpeg|png|gif'; $config["max_size"] = '1024'; $config["max_width"] = '400'; $config["max_height"] = '400'; $this->load->library('upload', $config); if(!$this->upload->do_upload()) { $this->data['error'] = $this->upload->display_errors(); print_r( $this->data['error']); } else { print_r("success"); } } } ``` View ``` <form role="form"> <div class="form-group"> <label for="recipient-name" class="control-label">Blog Title:</label> <input type="text" class="form-control" id="recipient-name"> </div> <div class="form-group"> <label for="message-text" class="control-label">Message:</label> <textarea class="form-control" id="message-text"></textarea> </div> <div class="form-group"> <label for="message-text" class="control-label">Upload image:</label> <img src="<?php echo base_url();?>assest/img/blank.png" alt="Blank image" id="uploadimg" class="img-thumbnail"> <input style="display:none" id="file" value=" " type="file" class="file" data-show-preview="false"> </div> </form> ``` Response C:\fakepath\Koala.jpg You did not select a file to upload. Please help