I am using Jquery Ajax to upload an image in Codeigniter, But the problem is the image does not get uploaded an I get alert Disallowed key Characters.Below is the model and view I am using.
View:
$("#upload_course_img").on('submit',function(e){
e.preventDefault();
$.ajax({
url: "<?php echo base_url();?>upload_course_image/upload_img",
type: 'POST',
cache: false,
data: new FormData(this),
processData:false,
success: function(data){
alert("data:"+data);
},
error: function(){
alert('Error while request..');
}
});
});
<form method="post" id="upload_course_img" enctype="multipart/form-data">
<input type="file" name="course_img"/>
<input type="submit" name="submit" value="Save" id="submit-id-submit"/>
</form>
Model:
public function upload_img()
{
if($this->input->post('course_img')) {
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = '10000';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
if (!$this->upload->do_upload())
{
}
else
{
}
}
}
this is another option to upload file using AJAX http://malsup.com/jquery/form/#file-upload
Just Try Like this
//Program a custom submit function for the form
$("form#data").submit(function(event){
//disable the default form submission
event.preventDefault();
//grab all form data
var formData = new FormData($(this)[0]);
$.ajax({
url: 'formprocessing.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {
alert(returndata);
}
});
return false;
});
If you really want to upload image using AJAX, use Dropzone JS.
It will really make your life easy
Check out the Dropzone.js Website
You just have to instantiate the dropzonejs
object and set the options
Dropzone.options.myAwesomeDropzone = {
paramName: "file", // The name that will be used to transfer the file
maxFilesize: 2, // MB
accept: function(file, done) {
if (file.name == "image.jpg") {
done("Naha, you don't.");
}
else { done(); }
}
};