Search code examples
phpjqueryajaxprogressindicator

jQuery $.ajax & PHP Email Progress Indicator


I am developing a custom emailing system for one of my clients as an add on for the CMS I built that I give to my clients. I am using jQuery Ajax to send all the information to a PHP file that formats the email, sends a query to MySQL to get all the email address from the database, and the sends the emails using the mail(). This takes some time to do, and I am wanting the jQuery ajax to display a progress bar for each time the PHP script sends an email. I have searched for something that is similar to success: function() that receives data from the PHP script through JSON allowing jquery to update the progress of the emailing.

Does anyone have a suggestion for this? Something like this is preferable:

 $.ajax({
      type: "POST",
      url: "example.com",
      data: {"test":"test","tester":"tester"},
      PROGRESS: function(data){
        $("div").html(data);
      },
      success: function(r){
        alert(r);
      }
    });

});

Solution

  • You can use the xhr object and attach an event listener to the progress event

    $.ajax({
        //...
        xhr: function() {
            var xhr = new window.XMLHttpRequest();
            xhr.addEventListener("progress", function(e) {
                var p = e.loaded / e.total;
                // update your progress bar here..
            });
            return xhr;
        }
    })