I'm making an upload website and I'm trying to add an upload progress bar. For some reason, the Ajax form I am using in my scripts is breaking the PHP code, therefore, stopping it from uploading.
When I remove the Ajax form, the Javascript runs fine and the PHP manages to upload the file, but with it in, it breaks. Any ideas? Much appreciated.
<input type="submit" name="sub" class="button" value="Submit" onclick="upload_image();">
<div class='progress' id="progress_div">
<div class='bar' id='bar1'></div>
<div class='percent' id='percent1'>0%</div>
</div>
<script>
function upload_image()
{
var bar = $('#bar');
var percent = $('#percent');
$('#myForm').ajaxForm({
beforeSubmit: function() {
document.getElementById("progress_div").style.display="block";
var percentVal = '0%';
bar.width(percentVal)
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal)
percent.html(percentVal);
},
success: function() {
var percentVal = '100%';
bar.width(percentVal)
percent.html(percentVal);
},
});
}
</script>
I'm using:
if(isset($_POST['sub']))
for the PHP
Is there any error message from PHP?
If your willing to change your dependency from ajaxForm to jquery-ajax-progress (https://github.com/likerRr/jq-ajax-progress), you can do it with the following.
This assumes that the file you access can be found at /upload.php
<?php
if(isset($_FILES['image'])) {
var_dump($_FILES['image']);
$image = $_FILES['image'];
move_uploaded_file($image['tmp_name'], $_FILES['image']['name']);
}
?>
<form action="upload.php" enctype="multipart/form-data" method="post">
<input type="file" name="image" id="image">
<input type="submit" name="sub" class="button" value="Submit">
</form>
<div class='progress' style="display: none;">
<div class='bar' ></div>
<div class='percent' >0%</div>
</div>
<style type="text/css">
.bar {
width: 0;
background: #ccc;
min-height: 1em;
}
</style>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="/js/jq-ajax-progress.js" ></script>
<script type="text/javascript">
var uploadForm = $('form[enctype="multipart/form-data"]');
var bar = $('.bar');
var percent = $('.percent');
$(uploadForm).submit(function (e) {
e.preventDefault();
$('.progress').css('display','block');
var formData = new FormData(uploadForm[0]);
$.ajax({
type: 'post',
url: $(uploadForm).attr('action'),
data: formData,
contentType: false,
processData: false
}).uploadProgress(function (e) {
// tracking uploading
if (e.lengthComputable) {
var percentage = Math.round((e.loaded * 100) / e.total);
updateProgressBar(percentage);
}
}).done(function (result) {
updateProgressBar(100);
// TODO: Perform other complete action
// console.log(result);
});
});
function updateProgressBar(percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal);
percent.html(percentVal);
}
</script>