Percentage in ajax requests

5

I wonder if it's possible to create a percentage in Ajax requests. For example: When the form is submitted it starts with 0% up to 100% (when complete)

My ajax:

index.php

<script src="jquery.js"></script>

<script>
$(function()
{
    $('form').submit(function(e)
    {
        e.preventDefault();

        var formData = new FormData();

        formData.append('image', $('#file').prop('files')[0]);

          $.ajax({
            url: 'upload.php',
            data: formData,
            type: 'post',
            success: function(response)
            {
                console.log(response)
            },
            processData: false,
            cache: false,
            contentType: false
          });
    });
});
</script>

<form method="post" enctype="multipart/form-data">
    <input type="file" id="file" />
    <input type="submit" />
</form>
    
asked by anonymous 10.12.2014 / 13:17

1 answer

4

I think you got the same code from the previous answer about " upload without refresh , "where I had also replied.

I did not add any progress event to it as it was a very simple example.

But if you add a few lines in this code, you can instead view the upload progress of a particular file. This is done through the xhr callback

<script src="jquery.js"></script>

<script>
$(function()
{
    $('form').submit(function(e)
    {
        e.preventDefault();

        var formData = new FormData();

        formData.append('image', $('#file').prop('files')[0]);

          $.ajax({
            url: 'upload.php',
            data: formData,
            type: 'post',
            xhr: function() { 
                var myXhr = $.ajaxSettings.xhr();
                if(myXhr.upload){ 
                    myXhr.upload.addEventListener('progress', progressHandlingFunction, false);
                }
                return myXhr;
            },
            success: function(response)
            {
                console.log(response)
            },
            processData: false,
            cache: false,
            contentType: false
          });
    });
});

function progressHandlingFunction(e){
    if(e.lengthComputable){
        $('#progress').attr({value:e.loaded,max:e.total});
    }
}
</script>
<progress value='0' id="progress"></progress>
<form method="post" enctype="multipart/form-data">
    <input type="file" id="file" />
    <input type="submit" />
</form>

Of course this becomes more visible for large files (since in smaller files the progress will arrive at most faster)

    
10.12.2014 / 15:35