I am a bit stuck with my thoughts on a wordpress project.
Outline:
- 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)
- From the response I expect a QR image and a OrderRef (done)
- QRCode needs to be prompted on page, user should scan
- With OrderRef from endpoint1, endpoint2 is called for status updates. The OrderRef must be the same string as from the first endpoint call
- Endpoint responses pending until the QR code is scanned or timed
- 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
- 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.
- 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
user24331749 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.