[英]WooCommerce ajax fetch order status & redirect to url
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. 我想使用ajax连续检查订单状态,如果我得到的订单状态为“处理中”,那么我想将客户重定向到特定的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
: 在
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');
?>
has_status is a method, that accepts an argument. has_status是一个方法,它接受一个参数。 It returns a boolean, not a string.
它返回一个布尔值,而不是字符串。
Maybe try $order->has_status( 'processing' );
也许尝试
$order->has_status( 'processing' );
. 。
Also - update the success
logic: 另外-更新
success
逻辑:
success : function( response ){
if (response === 'DESIRED_STATUS') {
window.location.href = "url to redirect";
}
}
Where, DESIRED_STATUS
is the status you're waiting for to make the redirect. 其中,
DESIRED_STATUS
是您正在等待进行重定向的状态。
Since you're making an HTTP request, it is possible for a race condition to happen. 由于您正在发出HTTP请求,因此可能发生竞争情况。
<script>
function fetchStatus()
{
jQuery.ajax({
url : '<?php echo admin_url( '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 ){
if (response === 'DESIRED_STATUS') {
window.location.href = "url to redirect";
} else {
fetchStatus();
}
}
});
}
fetchStatus();
</script>
This is the thing I did: 这是我所做的:
function fetchStatus()
{
jQuery.ajax({
url : '<?php echo admin_url( 'admin-ajax.php' ); ?>?action=fetch_order_status&order_id=<?php echo $order_id; ?>',
type : 'post',
dataType:"json",
error : function(response){
console.log(response);
},
success : function( response ){
console.log(response);
if (response.status == "processing") {
window.location.href = "URL to redirect";
} else {
fetchStatus();
}
}
});
}
fetchStatus();
</script>
and in function.php: 并在function.php中:
function fetch_order_status(){
$order = wc_get_order( $_REQUEST['order_id'] );
$order_data = $order->get_data();
echo json_encode(array("status"=>$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');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.