3

Situation: User uploads a number of photos via AJAX, then continues interacting with the website whilst a PHP script continues running in the background and generates a variety of thumbnails based on the uploaded photos.

Site config:

  1. jQuery AJAX (v1.9.1)
  2. PHP 5.4.7, FastCGI mode
  3. IIS 7.5, with gzip

Previous posts that I've referred to and tried to implement (but to no avail):

I have tried a huge number of script options based on the previous posts, however none seem to tell the AJAX script to let the user continue, whilst the PHP continues to process...

Example PHP code:

<?php
   // Save images to db, etc

   // Now tell AJAX to let the user continue, before generating thumbnails
   if(ini_get('zlib.output_compression')) { 
       ini_set('zlib.output_compression', 'Off'); // turn IIS gzip for this file
   }
   ob_end_clean();
   header("Connection: close");
   header("Content-Encoding: none"); //ensures gzip is not sent through
   ob_start();
      echo '123'; // 3 digit number will be sent back to AJAX
   $size = ob_get_length(); // should mean Content-Length = 3
   header("Content-Length: $size");
   ob_end_flush(); 
   flush(); 
   ob_end_clean();

   // Generate thumbnails, etc
?>

Example jQuery AJAX code:

$.ajax({
        type: 'POST',
        url: ajax_url,
        data: { foo: bar },
        beforeSend:function(){
            // 
        },
        success:function(data){
            alert(data); // Only seems to be firing once the thumbnails have been generated.
        }
    });

The response headers seem okay...

POST response headers as detected by Firebug

Question: How do I get AJAX to allow the user to continue once it has received the code from the middle of the PHP script, whilst the PHP script continues to generate the thumbnails?

Community
  • 1
  • 1
Paul
  • 804
  • 2
  • 13
  • 31

1 Answers1

1

If you run request, it will always wait until PHP Script finish executing, or there will be a timeout. So you cannot stop AJAX in middle, and keep PHP running. If you want to upload files, and then create thumbnails, but have info that files are uploaded, do it in two steps:

  1. upload files with AJAX -> return success
  2. run another AJAX request on success to get uploaded images (or thumbs in fact).

Thanks to that, thumbs can be also rendered later, when they are first time requested (even without ajax). If you don't want requesting and waiting for thumbs, use cron job on server, which will create thumbs for awaiting images.

gnysek
  • 319
  • 1
  • 15
  • Thanks @gnysek for your thoughts. However, I had thought based on the previous SO questions I had referred to, that this type of PHP/AJAX interaction was possible. Even blog posts like this seem to indicate that this is possible: http://www.zulius.com/how-to/close-browser-connection-continue-execution/ – Paul Mar 11 '13 at 11:30