I am working on a project where i must call a 3rd party API from client-side then process the response in PHP before displaying it in on the front end. So i planned it in my head like this:
- use getJSON to call the 3rd party API
- send response to PHP via AJAX
- put it in a variable and use it
Unfortunately i can't figure out how to put the response in a php variable and use it in my shortcode function.I am not a PRO developer, but in the last two days i've read anything related to this situation, so here is my current code:
The external API url supports params and i am constructing it depending what i need on the particular page, using shortcode atts. So the journey starts in add_shortcode callback function:
$url = theAPIurl //with parameters
$apinonce = wp_create_nonce('apinonce');
wp_add_inline_script('ajax-request', 'const apidata = '.json_encode( array( 'apiUrl' => $url , 'ajaxUrl' => admin_url( 'admin-ajax.php' ) , 'nonce' => $apinonce )) , 'before');
The enqueued scripts:
wp_register_script('ajax-request' , 'pathtomyjs' , array('jquery'), false, true);
wp_enqueue_script('ajax-request');
My JS file
$.getJSON(apidata.apiUrl , function(response_data){
$.ajax({
type: 'POST',
url: apidata.ajaxUrl,
data: {nonce: apidata.apinonce, action:'api_response', data:JSON.stringify(response_data) },
dataType:"json"
});
return false;
})
AJAX action hooks
add_action('wp_ajax_api_response' , 'kwpca_api_callback' );
add_action('wp_ajax_nopriv_api_response' , 'kwpca_api_callback' );
AJAX callback function
function kwpca_api_callback() {
check_ajax_referer('apinonce' , 'nonce');
$response = json_decode(stripslashes($_POST["data"]), true);
$data = wp_send_json($response);
}
Looking in browser dev tools->network, i can see both getJSON and admin-ajax requests being successful, the data is what i need, but i can't figure out how to pass it to my shortcode function.
If i call the function directly like $newdata = kwpca_api_callback()
, and var_dump($newdata)
, the output is -1 and no ajax calls are executed in network tab. At this point i'm clueless what to do next and i lost count how many times i've reverted the code trying possible solutions. Any help is very much appreciated
wp_safe_remote_get()
orwp_safe_remote_post()
to get the data from the API? It seems to me like you're adding unnecessary layers here—starting on the server side (the shortcode), moving to AJAX for the request, then trying to deliver the data from AJAX back to the server side for output.wp_remote_get()
but there were times when the response was not the expected data, but a message that the request limit has been reached. Also, the developers said that doing it server side, will always use the server IP, regardless of the arguments passed. Thanks for looking