Skip to main content

AJAX Monitoring Progress

AJAX - Monitoring Progress

Monitoring Progress in AJAX allows you to track the progress of AJAX requests, especially useful for long-running requests or file uploads. By monitoring progress, you can provide feedback to users, display progress bars, and enhance the user experience.


1. Tracking Progress with XMLHttpRequest

You can monitor progress using the native XMLHttpRequest object by listening to progress events such as 'loadstart', 'progress', 'abort', and 'load'.

Example:

// Monitoring progress with XMLHttpRequest
var xhr = new XMLHttpRequest();

xhr.open('GET', 'https://api.example.com/bigFile');
xhr.onloadstart = function() {
  console.log('Request started');
};

xhr.onprogress = function(event) {
  if (event.lengthComputable) {
    var percentComplete = (event.loaded / event.total) * 100;
    console.log('Progress:', percentComplete + '%');
  }
};

xhr.onload = function() {
  console.log('Request completed');
};

xhr.send();

In this example, we create a new XMLHttpRequest object and listen to progress events. We calculate the percentage of completion based on the loaded and total bytes of the request.


2. Monitoring Progress with jQuery AJAX

If you're using jQuery for AJAX requests, you can monitor progress using the xhr option in the AJAX settings.

Example:

// Monitoring progress with jQuery AJAX
$.ajax({
  url: 'https://api.example.com/bigFile',
  method: 'GET',
  xhr: function() {
    var xhr = new window.XMLHttpRequest();
    
    xhr.upload.addEventListener('progress', function(event) {
      if (event.lengthComputable) {
        var percentComplete = (event.loaded / event.total) * 100;
        console.log('Upload progress:', percentComplete + '%');
      }
    }, false);

    return xhr;
  },
  success: function(response) {
    console.log('Request completed');
  },
  error: function(xhr, status, error) {
    console.error('Error:', status, error);
  }
});

In this example, we use jQuery's AJAX function and specify a custom XMLHttpRequest object with an event listener for progress. We calculate the percentage of upload completion and log it to the console.


3. Conclusion

Monitoring Progress in AJAX is essential for providing feedback to users and enhancing the user experience, especially for long-running requests or file uploads. By tracking progress using native XMLHttpRequest or jQuery AJAX, developers can implement progress monitoring functionality and improve the usability of their web applications.

Comments