Reputation: 2177
I'm trying to create a progress bar for my form but it still doesn't work. After loading the form, I would like my progress bar to move from 0 percent to 100 and finish loading. I still can't see why my progress bar is not working.
My code looks like this
<form method="POST" enctype="multipart/form-data" name="newProductForm" id="newProductForm">
<input type="file" name="img" class="custom-input-file" accept=".jpg, .jpeg" required id="id_img">
<input type="text" name="category" class="form-control form-control-emphasized" id="category" placeholder="Wpisz kategorie..." maxlength="200" required>
<div class="progress">
<div id="progressBar" class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;">
0%
</div>
</div>
<button type="button" onClick="submitFunction();" class="btn btn-block btn-primary" id="buttonSubmitProduct">
<span style="display:block;" id="buttonText">
Submit
</span>
<span style="display:none;" id="buttonSipner">
Loading......
</span>
</button>
</form>
My AJAX and JS:
<script>
function submitFunction() {
document.getElementById('buttonSubmitProduct').disabled = true;
document.getElementById('buttonText').style.display = 'none';
document.getElementById('buttonSipner').style.display = 'block';
document.getElementById('newProductForm').submit();
}
$(document).ready(function() {
$('newProductForm').on('submit', function(event) {
event.preventDefault();
var formData = new FormData($('newProductForm')[0]);
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
console.log('Bytes Loaded: ' + e.loaded);
console.log('Total Size: ' + e.total);
console.log('Percentage Uploaded: ' + (e.loaded / e.total))
var percent = Math.round((e.loaded / e.total) * 100);
$('#progressBar').attr('aria-valuenow', percent).css('width', percent + '%').text(percent + '%');
}
});
return xhr;
},
type: 'POST',
url: '',
data: formData,
processData: false,
contentType: false,
success: function() {
location.replace("/?okey=smile");
}
});
});
});
</script>
I don't see any errors in the console. Why is my code not working?
Upvotes: 0
Views: 363
Reputation: 8135
What about use the progress HTML5 tag to do that?
//calling the function in window.onload to make sure the HTML is loaded
window.onload = function() {
var pos = 0;
var t = setInterval(move, 75);
function move() {
if(pos >= 400) {
clearInterval(t);
}
else {
pos += 4;
bar.value = pos/4;
}
}
};
#container {
width: 400px;
height: 50px;
position: relative;
}
#bar {
width: 400px;
height: 50px;
position: absolute;
}
progress {
text-align: center;
}
progress:after {
content: attr(value)'%';
}
progress:before {
content: 'progress ';
}
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<div id="container">
<progress id="bar" value="0" max="100"></progress>
</div>
</body>
</html>
Upvotes: 1