Reputation: 419
I'm trying to send a file form view to server via an ajax _call. Here is my form :
<form id="fileForm" name="fileForm" enctype="multipart/form-data">
<div class="row" >
<div class="span8" >
<label><strong>Please attach a file</strong></label>
<input style="margin-bottom:0" type="file" name="attach" id="attach" />
<button type="submit" class="btn btn-primary" onclick="do_upload()" ><i class="icon-camera icon-white"></i>Send</button>
</div>
</div>
</form>
And here is do_upload (in the same file):
<script type="text/javascript">
function do_upload()
{
var uploaded_file= $('#attach').val();
alert(uploaded_file); //prints the name of the uploaded file
$.ajax({
type:'POST',
url : '<?php echo site_url()."/public/hours/do_upload/"; ?>', //the path to my controller
data : uploaded_file,
cache: false,
contentType: 'multipart/form-data',
processData :false ,
success:function(data){
alert(' sucessful ajax call ');//is printed
}
});
}
</script>
And finally in public/hours (which is my controller), I have:
function do_upload () {
$config= array ('upload_path'=>'./uploads/','allowed_types'=>'pdf|gif|jpg|jpeg|docx', 'max_size'=>2048);
//loading upload
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('attach'))
{ $data = array('error' => $this->upload->display_errors());
var_dump($data);
exit;
}
else
{ $data = array('upload_data' => $this->upload->data('attach'));
var_dump($data);
exit;
}
}
Here is the result of the var_dump($data):
array(1) {
["error"]=>
string(43) "<p>You did not select a file to upload.</p>"
}
And firebug shows this error :
Form contains a file input, but is missing method=POST and enctype=multipart/form-data on the form. The file will not be sent.
Could anyone help me please? Thank you
Upvotes: 0
Views: 2980
Reputation: 104
Try type="button" or use <div class="btn btn-primary" onclick="do_upload()">..</div>
on
<button type="submit" class="btn btn-primary" onclick="do_upload()" ><i class="icon-camera icon-white"></i>Send</button>
It worked for me..
Upvotes: 1