2

I have a webpage that calls an AJAX script - ajax.php. I am using JQuery to send the AJAX requests.

The script ajax.php receives some arguments via$_REQUEST, based on that it starts its processing. The processing has multiple steps involved and at the end of the each step I want to send some feedback back to the page - for example:

  • Step 1 completed
  • Step 2 completed
  • ....

Once all the steps are completed - the script ajax.php will output a TXT file which I am outputting via:

header('Content-type: text/plain');
header('Content-Disposition: attachment; filename="output.txt"');

My questions are:

I have a div in the page where I want to show the user that Step 1 completed, Step 2 completed, ... If I use JQuery.ajax(), will the .done function called multiple times? If no, whats the best way to handle it? Can I use ob_implicit_flush in PHP to send 'Step x completed 'messages?

Finally, how will I handle the output of .txt file so that user's browser downloads it? I don't want to save the file on the server and then going into hassle of server disk space, cron jobs of deletes, etc.

I have the option of doing multiple AJAX requests - but again I don't want to do this as this will make my code logic pretty complex and I will have to save a lot of data in $_SESSION to be visible across requests which is again something that I don't want to do.

Ahmad
  • 474
  • 1
  • 4
  • 19

1 Answers1

0

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.

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();
                }
            }
        });
    }
</script>
Luffy
  • 1,317
  • 1
  • 19
  • 41
  • Thanks but it will result in sending multiple results to server. I guess I will have to break the function up into multiple pieces... – Ahmad Oct 08 '15 at 03:14