Skip to content

Instantly share code, notes, and snippets.

@carry0987
Last active January 23, 2020 14:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carry0987/2491899cca15e256970e1450f41e7a0b to your computer and use it in GitHub Desktop.
Save carry0987/2491899cca15e256970e1450f41e7a0b to your computer and use it in GitHub Desktop.
Get File Upload Progress in Ajax using jQuery

Progress Bar helps to display the file upload status in real-time.
You can get the upload progress in Ajax and show the percentage progress bar using jQuery.
The progress bar is very useful to make the file upload process user-friendly.
The following code snippet shows how to get the file upload progress in Ajax and make a progress bar with percentage using jQuery.

  • Use xhr option in $.ajax() method to handle the progress bar operation.
  • Create a new XMLHttpRequest object using JavaScript window.XMLHttpRequest() method.
  • The progress event of XMLHttpRequest upload property allows to get the total and loaded length.
  • Calculate the percentage and handle the process bar.
$.ajax({
    xhr: function() {
        var xhr = new window.XMLHttpRequest();
        xhr.upload.addEventListener("progress", function(evt) {
            if (evt.lengthComputable) {
                var percentComplete = (evt.loaded / evt.total) * 100;
                // Place upload progress bar visibility code here
            }
        }, false);
        return xhr;
    },
    type: 'POST',
    url: "upload.php",
    data: {},
    success: function(data){
        // Do something on success
    }
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment