I'm working on a script that will be used to show a progress bar when large amounts of data are exported. For this to work you need to know how many location you have in total, and keep that number somewhere.
When I run the below code outside of WordPress, then it works as expected.
It shows this output.
{"uncoded":"123"}
not null
not null
not null
not null
It's null on the first loop, so it grabs the value and after that the $total value is set, so it's not null anymore. But when I call it through AJAX the getTotal()
is always null. It should be null the first time, but not after that. It should contain the total amount of rows on the second attempt.
This is the code I'm using.
class progress {
private static $total = null;
public function getTotal() {
return self::$total;
}
public static function setTotal() {
self::$total = '123';
}
}
class batch extends progress {
function __construct() {
add_action( 'wp_ajax_batch_actions', array( $this, 'run' ) );
add_action( 'wp_ajax_nopriv_batch_actions', array( $this, 'run' ) );
}
public function run() {
if ( is_null( $this->getTotal() ) ) {
$this->setTotal();
$total = $this->getTotal();
echo json_encode( array( 'uncoded' => $total ) );
} else {
echo 'not null';
}
exit();
}
}
I'm a bit confused why this works fine without AJAX in WordPress, but as soon as you use the AJAX action it fails to remember the $total value. It's always null?
Does anyone have any idea why, and also how to make it work correctly with AJAX?
$total
persists or is "remembered" only on the same page load.