David Lences
David Lences

Reputation: 113

PHP + Mysql insert into + jQuery progress bar

I have problem with showing current inserted rows into mysql with query. Now I have this code in index.php:

  $('#nacitatATC').click(function() {
    $.ajax({
            xhr: function() {

                    var xhr = new window.XMLHttpRequest();
                    xhr.addEventListener("progress", function(e){
                        var p = (e.loaded / e.total)*100;
                        var prave = $("#progress").html();
                              $("#progress").html(prave+"<br>"+p);
                    });
                return xhr;

            }
            , type: 'post'
            , cache: false
            , url: "/sql.php"});

      });
  });

and in sql.php I have the php code with inserting data into mysql with for(). $i is the current inserting line and $pocet is total lines.

The problem is with show current inserting line with ajax. The code above shows in div #progress "100" when ajax finish loading.

I need show 1% 2% 3% 4%... 99% 100% Completed. Thanks for help!

Upvotes: 2

Views: 9918

Answers (1)

Erik255
Erik255

Reputation: 1473

I think php -> flush() is what you are looking for.

This Example works perfect on my php-apache on debian

see ajax-request-progress-percentage-log

PHP side:

header( 'Content-type: text/html; charset=utf-8' );
echo 'Begin ...<br />';
for( $i = 0 ; $i < 10 ; $i++ )
{
    echo $i . '<br />';
    flush();
    ob_flush();
    sleep(1);
}
echo 'End ...<br />';

site:& javascript:

<!doctype html>
<html>
<head>
    <title>Test Flush</title>
    <meta charset="utf-8">
    <script src="./js/jquery-2.0.3.min.js" type="text/javascript"></script>
<body>
<h1>Hello</h1>
<div id="progress">0%</div>

<p>
</p>
<script type="text/javascript">
    $('h1').click(function() {
    $.ajax({
            xhr: function() {

                    var xhr = new window.XMLHttpRequest();
                    xhr.addEventListener("progress", function(e){
                        console.log(e.currentTarget.response);
                        $("#progress").html(e.currentTarget.response);
                    });
                return xhr;

            }
            , type: 'post'
            , cache: false
            , url: "testFlush.php"
        });

    });

</script>
</body>

Also have a look at Rogers Answer in how-to-flush-output-after-each-echo-call He found issues in the apache setup

Upvotes: 1

Related Questions