plugin development – getJSON response to PHP
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
Leave an answer