0

I am trying to add a simple progress bar/number to my PHP image upload. If javascript is enabled, this script shall work, but now, it immediatly shows 100%, before everything has been uploaded, and then it shows "images are beeing processed", also too early, I think.

Something must be wrong:

$('form#uploadform').submit(function(){
var formdata = $('form#uploadform').serialize();
$('p.isloading').show();

$.ajax({
xhr: function () {
    var xhr = new window.XMLHttpRequest();
    xhr.upload.addEventListener("progress", function (evt) {
        if (evt.lengthComputable) {
            var percentComplete = evt.loaded / evt.total;
            $('#uploadprogress').text(percentComplete * 100 + '%');
        }
    }, false);
    xhr.addEventListener("progress", function (evt) {
        if (evt.lengthComputable) {
            var percentComplete = evt.loaded / evt.total;
            $('#uploadprogress').text(percentComplete * 100 + '%');
        }
    }, false);
    return xhr;
},
type: 'POST',
url: "/upload",
data: formdata,
success: function (data) { $('#uploadprogress').text('images are being processed'); }
});
//return false;
});

I want a simple way to show how much is already uploaded, but it seems I am doing it wrong. Any help is appreciated.

haheute
  • 2,129
  • 3
  • 32
  • 49

1 Answers1

0

This answer was on the link provided by @Amarnadh Meda.

JavaScript -

$(function() {

var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');

$('form').ajaxForm({
    beforeSend: function() {
        status.empty();
        var percentVal = '0%';
        bar.width(percentVal);
        percent.html(percentVal);
    },
    uploadProgress: function(event, position, total, percentComplete) {
        var percentVal = percentComplete + '%';
        bar.width(percentVal);
        percent.html(percentVal);
    },
    complete: function(xhr) {
        status.html(xhr.responseText);
    }
});
}); 

HTML -

<form action="file-echo2.php" method="post" enctype="multipart/form-data">
    <input type="file" name="myfile"><br>
    <input type="submit" value="Upload File to Server">
</form>

<div class="progress">
    <div class="bar"></div >
    <div class="percent">0%</div >
</div>

<div id="status"></div>

Edit #1:

Found similar question here. File upload progress bar with jQuery

Community
  • 1
  • 1
Script47
  • 14,230
  • 4
  • 45
  • 66