Upload file using AJAX with CodeIgniter
I have tried many examples. It did succeed ever, but sometimes it didn't load. This is my code:
<div class="fallback">
<form method="POST" id="quiz_file" action="<?php echo site_url('home/upload_quiz/' . $kelas);?>" enctype="multipart/form-data">
<input name="filequiz" id="filequiz" type="file" />
</form>
</div>
This is the ajax code:
$('#submitquiz').on('click', function(event) {
var inputFile = $('input[name=filequiz]');
var uploadURI = $('#quiz_file').attr('action');
document.getElementById('submitquiz').disabled = true;
var fileToUpload = inputFile[0].files[0];
// make sure there is file to upload
if (fileToUpload != 'undefined')
{
// provide the form data
// that would be sent to sever through ajax
var formData = new FormData();
formData.append("file", fileToUpload);
console.log("Process");
// now upload the file using $.ajax
$.ajax({
url: uploadURI,
type: 'post',
data: formData,
processData: false,
contentType: false,
beforeSend: function ( xhr ) {
console.log("progress");
console.log(xhr);
console.log(formData);
},
success: function(data)
{
console.log("finish");
console.log(data);
}
This is my controller:
function upload_quiz($kelas)
{
$temp = explode(".", $_FILES["filequiz"]["name"]);
$extension = end($temp);
$new_name = time() . "." . $extension;
$config['upload_path'] = './assets/images/quiz_images/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = 2000;
$config['file_name'] = $new_name;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
$session_data = $this->session->userdata('logged_in');
$data['user_name'] = $session_data['user_name'];
$data['kelas'] = $kelas;
if ( ! $this->upload->do_upload('filequiz'))
{
$data['error'] = array('error' => $this->upload->display_errors());
$this->load->view('course', $data);
}
else
{
$data['status'] = array('upload_data' => $this->upload->data());
$quiz_name = $this->input->post('quiz_name');
$this->load->model('Model');
if($this->Model->input_quiz($quiz_name,$new_name,$kelas) == TRUE)
{
$this->load->view('course', $data);
}
elseif($this->Model->input_quiz($quiz_name,$new_name,$kelas) == FALSE)
{
$this->load->view('course', $data);
}
}
}
After I submit with the button, the AJAX response when I use console.log (data). And it says that the first line in my controller function ($ temp) is UNDIFEND INDEX: filequiz.
What might be missing?
source to share
Change this
$temp = explode(".", $_FILES["filequiz"]["name"]);
in the following way
$temp = explode(".", $_FILES["file"]["name"]);
and if ( ! $this->upload->do_upload('filequiz'))
beforeif ( ! $this->upload->do_upload('file'))
when posting filename file
with JS notfilequiz
However, if you want to use the name filequiz
, then change the ajax code from
formData.append("file", fileToUpload);
to
formData.append("filequiz", fileToUpload);
source to share