I want to check the order status continuously using ajax and if I get the order status is “processing” then I want to redirect the customer to a specific URL. I tried below snippet but it didn’t work.
<script>
function fetchStatus()
{
jQuery.ajax({
url : '<?php echo site_url(); ?>/wp-admin/admin-ajax.php?action=fetch_order_status&order_id=<?php echo $order->get_order_number(); ?>',
type : 'post',
error : function(response){
console.log(response);
},
success : function( response ){
window.location.href = "url to redirect";
}
});
}
setInterval(fetchStatus, 1000);
</script>
In functions.php
:
<?php
function fetch_order_status(){
$order = wc_get_order( $_REQUEST['order_id'] );
$order_data = $order->get_data();
if($order->has_status == 'processing'){
echo $order_data['status'];
}
die();
}
add_action('wp_ajax_nopriv_fetch_order_status', 'fetch_order_status');
add_action('wp_ajax_fetch_order_status','fetch_order_status');
?>
2
Answers
This is the thing I did:
and in function.php:
has_status is a method, that accepts an argument. It returns a boolean, not a string.
Maybe try
$order->has_status( 'processing' );
.Also – update the
success
logic:Where,
DESIRED_STATUS
is the status you’re waiting for to make the redirect.Answer without race conditions
Since you’re making an HTTP request, it is possible for a race condition to happen.