getJSON response to PHP

After more reading and testing, i’ve realised that i misunderstood how AJAX works, therefore it was never gonna work the way i thought it would. For those who come across this, i hope this will help.

In shortcode function i generated the api url with params specific to the page where shortcode is called. eg [my_shortcode list="employees" type="json" sort="DESC"].

I used wp_add_inline_script() to send data from PHP to my custom JS. Added an empty div with unique id, for AJAX to insert my HTML

my_shortcode_callback($atts){
  $atts= shortcode_atts( array(
  /* params for constructing API url to be called */
   ), $atts);
$apiUrl="https://somedomain.xyz/?list=employees&type=json&sort=desc";
/*Pass the api url, ajax url and nonce to the js file. 
 The recommended way but wp_localize_script works too */
wp_add_inline_script('ajax-request', 'const apidata=".json_encode( array( "apiUrl' => $apiUrl , 'ajaxUrl' => admin_url( 'admin-ajax.php' ) , 'nonce' => wp_create_nonce('apinonce)  )) , 'before');
$html="<div id="ajax-html"></div>"; 
return $html;
} 

The enqueued scripts:

wp_register_script('ajax-request' , 'pathtomyjs' , array('jquery'), false, true);
wp_enqueue_script('ajax-request');

My JS file

The below code is calling the 3rd party API then send the response to the server via AJAX POST. On success, will insert server response in <div id="ajax-html"></div>

$.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",
          cache:false,
          success: function( response ){
        $('#ajax-html').html(response['data'])
      },
    error: function( error ){
        console.log('AJAX error callback....');
        console.log(error);
    }
        });
  })

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');
  if(isset($_POST['data'])){
    $response = json_decode(stripslashes($_POST['data']), true);
    // process received data in PHP. EG:
    $html="<ul>";
    foreach($response as $data){
      $html .= '<li>'.$data['title'].'</li>';
    }
    $html .= '</ul>' 
  } 
  $data = wp_send_json_success($html);
}

HTML Output

<div id="ajax-html">
  <ul>
    <li>Title1</li>
    <li>Title2</li>
    <li>Title3</li>
    <li>etc...</li>
  </ul>
</div>

The above is a stripped version of my code to show how to get data from an external api using AJAX then create shortcode to display received data. I hope it will help somebody.