Send AJAX results but continue processing in PHP

I'm using AJAX to update some values in a database. All has worked wonderfully with that, but now I would like to implement some logging stuff. The logging functions look like they are going to take a fair amount of processing time, and theirs no reason that the user should have to wait for them to finish to see their AJAX results.

So, I'm trying to find a way to send AJAX results and still continue processing on the server side. My research has brought up the ignore_user_abort function, but apparently I'm not using it correctly.

This guide is what I'm basing my code off.

Here's my javascript (Jquery) :

 $.ajax({
            type: "GET",
            url: "ajax.php",
            data: { "mydata": mydata },
            success: function(msg) {
                    $("span#status").fadeOut(200, function() {
                            $("span#status").html(msg);
                            $("span#status").fadeIn(200);
                    });

            }
    });

And my PHP:

    $response = "This is my response";

    //Begin code from link
    ob_end_clean();
    header("Connection: close");
    ignore_user_abort(true);
    ob_start();
    echo $response;
    header("Content-Length: " . mb_strlen($response));
    ob_end_flush();
    flush();
    //End code from link

    echo "I should not see this text";

Unfortunately, I am seeing that text after the flush();

Any ideas?

Update - Fixed: I figured out my error. After copying word for word tons of different code suggestions, I figured it must have been an error in my apache/php configuration. Turns out I need to add two lines to force apache not to buffer my results:

apache_setenv('no-gzip', 1);
ini_set('zlib.output_compression', 0);

Answers:

Answer

Well, you would see it, wouldn't you? You told it to echo!

In all seriousness, your example should work. It seems that code is executing after the flush, so you should be able to do your logging if the flush sent the request to the browser.

Answer

The PHP script cannot tell the browser to close the connection and not wait for further data. Using flush(); only sends the current output down the chain, to the web server, but it does not guarantee it will arrive to the browser immediately. The web server may cache the output until the PHP script completes the execution.

As the OP wrote in the last paragraph, the solution is to configure Apache to not buffer the results.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.