I’m engaged on a mission the place i have to name a third get together API from client-side then course of the response in PHP earlier than displaying it in on the entrance finish. So i deliberate it in my head like this:
- use getJSON to name the third get together API
- ship response to PHP by way of AJAX
- put it in a variable and use it
Sadly i can not determine tips on how to put the response in a php variable and use it in my shortcode perform.I’m not a PRO developer, however within the final two days i’ve learn something associated to this example, so right here is my present code:
The exterior API url helps params and i’m developing it relying what i want on the actual web page, utilizing shortcode atts. So the journey begins in add_shortcode callback perform:
$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 )) , 'earlier than');
The enqueued scripts:
wp_register_script('ajax-request' , 'pathtomyjs' , array('jquery'), false, true);
wp_enqueue_script('ajax-request');
My JS file
$.getJSON(apidata.apiUrl , perform(response_data){
$.ajax({
sort: 'POST',
url: apidata.ajaxUrl,
information: {nonce: apidata.apinonce, motion:'api_response', information:JSON.stringify(response_data) },
dataType:"json"
});
return false;
})
AJAX motion hooks
add_action('wp_ajax_api_response' , 'kwpca_api_callback' );
add_action('wp_ajax_nopriv_api_response' , 'kwpca_api_callback' );
AJAX callback perform
perform kwpca_api_callback() {
check_ajax_referer('apinonce' , 'nonce');
$response = json_decode(stripslashes($_POST["data"]), true);
$information = wp_send_json($response);
}
Wanting in browser dev tools->community, i can see each getJSON and admin-ajax requests being profitable, the information is what i want, however i can not determine tips on how to go it to my shortcode perform.
If i name the perform instantly like $newdata = kwpca_api_callback()
, and var_dump($newdata)
, the output is -1 and no ajax calls are executed in community tab. At this level i am clueless what to do subsequent and that i misplaced depend what number of occasions i’ve reverted the code attempting potential options. Any assist could be very a lot appreciated