dongtie0929 2019-08-07 10:59
浏览 168

WooCommerce ajax获取订单状态并重定向到网址

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条回答 默认 最新

  • drip5880 2019-08-07 11:12
    关注

    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:

        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.

    Answer without race conditions

    Since you're making an HTTP request, it is possible for a race condition to happen.

    <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>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100