Correct Setup WordPress for refreshing API data on server until

I am a bit stuck with my thoughts on a wordpress project.

Outline:

  1. On page load an API call to endpoint1 should be made (I use the plugin WPgetAPI for this matter, it works for getting POST data for me)
  2. From the response I expect a QR image and a OrderRef (done)
  3. QRCode needs to be prompted on page, user should scan
  4. With OrderRef from endpoint1, endpoint2 is called for status updates. The OrderRef must be the same string as from the first endpoint call
  5. Endpoint responses pending until the QR code is scanned or timed
  6. When status is switching to complete in the API endpoint response the javascript loop should stop and it should be prompted a success message on the page
  7. I start the page load and the functions for calling the API are currently placed in my themes functions.php, once page load is done, call 1 is facilitated, js calls the ajax refreshing.
  8. The javascript is separated file called my-script.js

My problem:

For versatility, I want to use this on different spaces on my page, I insert this with WPCode Shortcode into the page. That works!

On page load the api returns correctly a OrderRef and I can prompt QR code. That works!

The logs in browser console indicates that in the Javascript and php page where different orderRefs used, I could contain the problem, but I am not really coming there that the javascript. The logs now indicate same orderRef is used:

[Log] JQMIGRATE: Migrate is installed with logging active, version 3.4.1 (jquery-migrate.js, line 104)
[Log] OrderRef set for AJAX: – "e1e012f1-6b6d-44d8-9473-1d164b151230" (test-wp-api-stage, line 1250)
[Log] OrderRef in the Javascript file: – "e1e012f1-6b6d-44d8-9473-1d164b151230" (my-script.js, line 2)
[Log] Sending AJAX request with data: – {action: "check_status", OrderRef: "e1e012f1-6b6d-44d8-9473-1d164b151230"} (my-script.js, line 5)
[Log] AJAX call successful. Response: – "" (my-script.js, line 15)

I do not really come to success building the loop so that WordPress manages to facilitate the refreshing of the status in endpoint2 function (), updates the page with response status and then ends the javascript once the status is completed.

My excerpt from the functions.php where I enqueue the scripts and set the functions for calling the endpoints.

function prepare_global_api_data() {
    global $globalApiData;
    if (!did_action('wp')) {
        return;  
    }
    $response = wpgetapi_endpoint('bank_id', 'endpoint1');
    if ($response && isset($response['apiCallResponse']['Response'])) {
        $globalApiData = [
            'OrderRef' => $response['apiCallResponse']['Response']['OrderRef'],
            'QrImage' => $response['apiCallResponse']['Response']['QrImage']
        ];
    } else {
        $globalApiData = ['OrderRef' => 'default-value', 'QrImage' => ''];
    }
    error_log('API Data prepared: ' . print_r($globalApiData, true));
}
add_action('wp', 'prepare_global_api_data'); 

// Localize script after making sure it's enqueued
function generate_and_enqueue_scripts() {
    global $globalApiData;
    wp_enqueue_script('jquery');
    wp_enqueue_script('my-script', get_template_directory_uri() . '/scripts/my-script.js', array('jquery'), '1.0.0', true);
    
    wp_localize_script('my-script', 'my_script_vars', [
        'OrderRef' => $globalApiData['OrderRef'],
        'ajax_url' => admin_url('admin-ajax.php')
    ]);
}
add_action('wp_enqueue_scripts', 'generate_and_enqueue_scripts');

// AJAX callback 
function check_status_callback() {
    if (empty($_POST['OrderRef'])) {
        echo 'Error: OrderRef is missing.';
        wp_die();
    }
    $OrderRef = sanitize_text_field($_POST['OrderRef']);
    $fields = ['OrderRef' => $OrderRef];
    $response2 = wpgetapi_endpoint('bank_id', 'endpoint2', ['body_variables' => $fields]);

    wp_die();
}
add_action('wp_ajax_check_status', 'check_status_callback');
add_action('wp_ajax_nopriv_check_status', 'check_status_callback');

The code snippet on my page.php

<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

$response = wpgetapi_endpoint('bank_id', 'endpoint1'); // First API call
if (is_array($response) && !empty($response['authResponse']) &&  is_array( $response['authResponse']['Success'])) {
    if (!empty($response['apiCallResponse']) && $response['apiCallResponse']['Success']) {
        $OrderRef = $response['apiCallResponse']['Response']['OrderRef']; // Store OrderRef in variable
        $autoStartToken = $response['apiCallResponse']['Response']['AutoStartToken']; // Capture AutoStart Token
        $qrImage = $response['apiCallResponse']['Response']['QrImage']; // Capture QR Image URL
        error_log('OrderRef set from endpoint1: ' . $OrderRef);
    }
}

// Ensure all variables are defined even if not set initially
$autoStartToken = $response['apiCallResponse']['Response']['AutoStartToken'] ?? 'Not Available';
$qrImage = $response['apiCallResponse']['Response']['QrImage'] ?? '';
?>

<style>
    .api-response {
        text-align: center;
    }
    .static-block, .dynamic-status {
        border: 1px solid #ccc;
        padding: 10px;
        margin-top: 20px;
        text-align: left;
    }
</style>

<div class="api-response">
    <div id="qrCodeContainer">
        <?php if (isset($OrderRef)): ?>
            Authentication successful. <br>
            Order Reference: <?php echo esc_html($OrderRef); ?><br>
            AutoStart Token: <?php echo esc_html($autoStartToken); ?><br>
            <img src="<?php echo esc_url($qrImage); ?>" alt="QR Code" id="qrCode"><br>
        <?php else: ?>
            Failed to authenticate or retrieve the Order Reference.
        <?php endif; ?>
    </div>

    <!-- Dynamic content area for AJAX updates -->
    <div id="statusMessageContainer" class="dynamic-status">
        Please scan the QR code. Status updates will appear here after scanning.
    </div>
</div>

<script type="text/javascript">
    // Immediately output the OrderRef into JavaScript context
    var my_script_vars = {
        OrderRef: '<?php echo $OrderRef ?? ''; ?>',
        ajax_url: '<?php echo admin_url('admin-ajax.php'); ?>'
    };
    console.log("OrderRef set for AJAX in PHP file:", my_script_vars.OrderRef); // Log this to console for debugging
</script>

The javascript .js
jQuery(document).ready(function($) {
    function checkStatus() {
        console.log('Making AJAX call with OrderRef:', my_script_vars.OrderRef);

        $.ajax({
            url: my_script_vars.ajax_url,
            type: 'POST',
            data: {
                action: 'check_status',
                OrderRef: my_script_vars.OrderRef
            },
            success: function(response) {
                console.log('AJAX call successful. Response:', response);
                // Update only the status message container
                $('#statusMessageContainer').html(response);
            },
            error: function(xhr, status, error) {
                console.error('AJAX call failed. Error:', error);
                $('#statusMessageContainer').html('<p>Error fetching data. Please try again.</p>');
            }
        });
    }

    // Set an interval to call checkStatus every 5 seconds (5000 milliseconds)
    setInterval(checkStatus, 5000);
});

Could you help me finding the problem with me how I get these 3 parts together so I can make a working process why the response from the endpoint2 call is not correctly showing.

The log [Log] AJAX call successful. Response: – “” (my-script.js, line 13) indicates that the javascript has no OrderRef, but I really don’t understand why.

Thanks

Tried several debugging approaches and logged the files, restructered the code, but I can’t find the error of the missing OrderRef

New contributor

user24331749 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật