1

I try to use jQuery AJAX for my goal but I have a problem.

$('#go').on('click',function(evt){
    evt.preventDefault();
    $(this).hide();
    $('#progress-bar').show();

    console.log('starting ajax request');
    $.ajax({
        xhr: function () {
            var xhr = new window.XMLHttpRequest();
            xhr.addEventListener('progress', function (e) {
                console.log(e);
                if (e.lengthComputable) {
                    $('.progress-bar').css('width', '' + (100 * e.loaded / e.total) + '%');
                }
            });
            return xhr;
        },

        type: 'POST',
        url: 'core.php',
        data: {},
        complete: function (response, status, xhr) {
            console.log(response);
            $('.desc').html(response.responseText);
        }
    });

});
.container-fluid {
 padding-top: 20px;
}
#progress-bar {
 margin-top: 20px;
 display: none;
 width: 100%;
}
<html>
<head>
 <link rel="stylesheet" href="style.css">
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
 <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
  <body>
 <div class="container-fluid">
  <a class="btn btn-default" id="go">Let's go!</a>
  <div class="progress" id="progress-bar">
   <div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width:40%">

   </div>
  </div>
  <div class="desc">

  </div>
 </div>
 <script src="ajax.js"></script>
</body>
</html>

In core.php I should do some functions with arrays. For example, it would be:

<?php
$sum = 0;
for ($i=0; $i<9999; $i++) {
    $sum++;
}
?>

My javascript structure doesn't work. I know that it's because of e.lengthComputable in xhr. Also I found out that core.php headers consist Content-Length: 0. Ok. But what should I do to do my ajax request properly and have dynamic progress bar?

Thank you!

Yuriy Faktorovich
  • 67,283
  • 14
  • 105
  • 142
Dmitry Shulga
  • 588
  • 1
  • 6
  • 19
  • I am not doing any front-end development, but strictly from scripting standpoint php buffers its output. you can disable it with ob_implicit_flush(); and make php script return things to you as it goes. Then you can monitor its output and act accordingly. – Dimi Feb 10 '17 at 21:09
  • @Dimi if I add ob_implicit_flush(); at the beginning of core.php, it doesn't help – Dmitry Shulga Feb 10 '17 at 21:40

0 Answers0