Percentage of ajax requests

Asked

Viewed 674 times

5

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

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>
  • Hey Hey, I’m talking about percentage progress on ajax requests, he’s talking about page load progress. @Renan

  • @Earendul ......

  • Moderator’s note: If it is duplicate, it is not the question that has been marked. Reopening.

1 answer

4


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

I didn’t add any event related to the press because it was a very simple example.

But, if we add some lines in this code, it is possible to display the upload progress of a particular file. This is done through the callback xhr

<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 to large files (since in smaller files the progress will reach maximum faster)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.