'Wordpress multiple ajax post requests, get_option does not show changes from later ajax post requests

I have a long-running post request handler that batch processes items. I want the user to be able to cancel this batch at any time by sending another post request. I have a flag that is stored in wp_options, however, the later cancel request does not appear to be able to be read by the first long-lived post request handler.

Example:

add_action('wp_ajax_batch', 'my_ajax_batch_handler');

function my_ajax_batch_handler()
{
  update_option('batch_state', 'running');
  // process items one by one, if the batch_state is ever 'cancelled', then quit.
  foreach ($values as $item) {
      // $batch_state is never 'cancelled' here, always 'running' even when it has been 
      // set to 'cancelled' in the following function.
      $batch_state = get_option('batch_state');
      if (!batch_state or batch_state == 'cancelled') {
         break;
      }
  }
}

add_action('wp_ajax_cancel_batch', 'my_ajax_cancel_batch_handler');

function my_ajax_cancel_batch_handler()
{
  update_option('batch_state', 'cancelled');
  // batch_state is cancelled here, but this change does not reflect in the
  // loop in the previous function.
}

Does Wordpress/php have isolated environments for each ajax post request?



Solution 1:[1]

I ended up solving this issue by clearing the cache before the get_option call in the loop.

add_action('wp_ajax_batch', 'my_ajax_batch_handler');

function my_ajax_batch_handler()
{
  update_option('batch_state', 'running');
  foreach ($values as $item) {
      // clear cache
      wp_cache_flush();
      wp_cache_delete('batch_state');
      $batch_state = get_option('batch_state');
      if (!batch_state or batch_state == 'cancelled') {
         break;
      }
  }
}

Not sure why this behavior exists, but clearing the cache solves it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 chewinggum