简体   繁体   中英

Use Ajax to show progress of a PHP script called by another Ajax request

I make a jQuery Ajax call to a PHP script that runs for a decent amount of time (between 1- seconds and 3 minutes). It constantly logs a percentage of completion in a database. How can I continually run another Ajax request at the same to report the percentage complete from the MySQL database to the user?

EDIT I understand how to use a separate PHP script to query the database, so my question is more how to set up the JavaScript and Ajax calls

After your AJAX call to kick off your process, you could make another AJAX call in a loop which requests, returns, and presents the current percentage complete until it reaches 100%. Basically, one AJAX call to initiate the process and then a series of calls which check status.

Update: Here is some simple JavaScript to achieve what you want:

<script>
function startProcess() {
    //start your long-running process
    $.ajax(
            {
                type: 'GET',
                url: "/longRunningProcess",
                async: true,
                success:
                    function (data) {
                        //do something - your long process is finished
                    }
            });
}
function getStatus() {
    //check your progress
    $.ajax(
            {
                type: 'GET',
                url: "/checkProgress",
                async: true,
                success:
                    function (data) {
                        //assume the data returned in the percentage complete
                        var percentage = parseInt(data);

                        //write your status somewhere, like a jQuery progress bar?

                        if (percentage < 100) {
                            //if not complete, check again
                            getStatus();
                        }
                    }
            });
}

You will probably need another URL to call that polls progress from the database. In other words, a different PHP script that reports progress. The Ajax call will probably use timeout or whatever fancy stuff jQuery has to schedule itself periodically (until the server call reports completion).

Remember to handle exceptional cases where the server side processing dies (and thus never completes!)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM