I'm new to jQuery/Ajax and I am trying to upload a file like so:
var fd = new FormData();
fd.append('file', file);
$.ajax({
xhr: function() {
var xhrobj = $.ajaxSettings.xhr();
if (xhrobj.upload) {
xhrobj.upload.addEventListener('progress', function(e) {
var percent = 0;
if (e.lengthComputable) {
percent = Math.floor(e.loaded / e.total * 100);
}
progressDiv.find('progress').val(percent);
progressDiv.find('b').html(percent + '%');
});
}
},
type: 'POST',
url: 'upload.php',
data: fd,
success: function(data) {
progressDiv.find('progress').val(100);
progressDiv.find('b').html('100%');
alert(data);
},
error: function() {
alert('Error uploading!');
}
});
My upload.php
file looks like this:
<?php
file_put_contents('log.txt', "LOG\n");
file_put_contents('log.txt', implode(', ', $_FILES) . "\n", FILE_APPEND);
$target = 'upload/' . basename($_FILES['file']['name']);
if (move_uploaded_file($_FILES['file']['tmp_name'], $target)) {
file_put_contents('log.txt', "SUCCESS\n", FILE_APPEND);
} else {
file_put_contents('log.txt', "FAILURE\n", FILE_APPEND);
}
?>
The problem is that the progress bars are remaining at 0 and the no alert ever appears. Also nothing is being written to the log
file, meaning that upload.php
is not even being called.
What am I doing wrong?
EDIT:
After searching for a while I stumbled across this nifty little question: Submitting a file with jQuery.ajax gives TypeError
So adding contentType: false
and processData: false
seems to have done something. Now I get the alert "Error uploading", but I still don't think upload.php
is being called as nothing is being written to log. Commenting out the xhr stuff after making those changes allows the upload to complete. Now the question becomes what is wrong with the xhr stuff?