I have upload form that allows users to upload multiple files. I decided that a progress bar would be good if the files are quite large. Below is my source code. I am new to jquery normally I would just php but I find that ajax is more user friendly.
<div id="new_upload">
<div class="close_btn"></div>
<div id="uploads"></div>
<form action="global.func/file_upload.php" method="post" enctype="multipart/form-data" id="upload_file">
<fieldset><legend>Upload an image or video</legend>
<input type="file" id="file" name="file[]" placeholder="Upload Image or Video" multiple /><input type="submit" value="upload file" id="upload_file_btn" required />
</fieldset>
<div class="bar">
<div class="bar_fill" id="pb">
<div class="bar_fill_text" id="pt"></div>
</div>
</div>
</form>
</div>
<script>
function OnProgress(event, position, total, percentComplete){
//Progress bar
console.log(total);
$('#pb').width(percentComplete + '%') //update progressbar percent complete
$('#pt').html(percentComplete + '%'); //update status text
}
function beforeSubmit(){
console.log('ajax start');
}
function afterSuccess(data){
console.log(data);
}
$(document).ready(function(e) {
$('#upload_file').submit(function(event){
event.preventDefault();
var filedata = document.getElementById("file");
formdata = new FormData();
var i = 0, len = filedata.files.length, file;
for (i; i < len; i++) {
file = filedata.files[i];
formdata.append("file[]", file);
}
formdata.append("json",true);
$.ajax({
url: "global.func/file_upload.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
dataType:"JSON",
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
beforeSubmit: beforeSubmit,
uploadProgress:OnProgress,
success: afterSuccess,
resetForm: true
});
});
});
</script>
The image upload works fine, the array send to ajax but the progress bar doesn't move. In fact the console.log for the two functions called need to produce this don't appear either. Is there a correct way to call the functions in my ajax request that would get this progress bar to work.
beforeSubmit: beforeSubmit, uploadProgress:OnProgress, success: afterSuccess,
NOTE that this function 'success: afterSuccess' is working as the console is displaying my data.
You must use a custom XMLHttpRequest to do this with AJAX and jQuery. There's an example here: How can I upload files asynchronously?
This is your HTML form
This is your JQuery and ajax. By default the fileInput is hidden.
Upload Button clicked
Your php code looks like this