Home > other >  Unexpected token A in JSON at position 0 (php) curl on api call
Unexpected token A in JSON at position 0 (php) curl on api call

Time:07-19

Hi im getting unexpected toke a in json at position 0 when i fetch the url. so i checked what im getting. when i console.log i get Array0; i dont how i can send the json to js. so here what i wanted is to use multi_thread_curl function to send multiple api request at the same time.so im getting array of two different content. one is from facebook and other one is from instagram. however when i try to send it over admin_ajax.php to js . i get Unexpected token A in JSON at position 0 error. i dont know what im doing wrong on this code. i will place the js code below as well.

function multi_thread_curl($urlArray, $optionArray, $nThreads) {

    //Group your urls into groups/threads.
    $curlArray = array_chunk($urlArray, $nThreads, $preserve_keys = true);
  
    //Iterate through each batch of urls.
    $ch = 'ch_';
    foreach($curlArray as $threads) {      
  
        //Create your cURL resources.
        foreach($threads as $thread=>$value) {
  
        ${$ch . $thread} = curl_init();
  
          curl_setopt_array(${$ch . $thread}, $optionArray); //Set your main curl options.
          curl_setopt(${$ch . $thread}, CURLOPT_URL, $value); //Set url.
  
          }
  
        //Create the multiple cURL handler.
        $mh = curl_multi_init();
  
        //Add the handles.
        foreach($threads as $thread=>$value) {
  
        curl_multi_add_handle($mh, ${$ch . $thread});
  
        }
  
        $active = null;
  
        //execute the handles.
        do {
  
        $mrc = curl_multi_exec($mh, $active);
  
        } while ($mrc == CURLM_CALL_MULTI_PERFORM);
  
        while ($active && $mrc == CURLM_OK) {
  
            if (curl_multi_select($mh) != -1) {
                do {
    
                    $mrc = curl_multi_exec($mh, $active);
  
                } while ($mrc == CURLM_CALL_MULTI_PERFORM);
            }
  
        }
  
        //Get your data and close the handles.
        foreach($threads as $thread=>$value) {
  
        $results[$thread] = curl_multi_getcontent(${$ch . $thread});
  
        // curl_multi_remove_handle($mh, ${$ch . $thread});
  
        }
  
        //Close the multi handle exec.
        curl_multi_close($mh);
  
    }
  
  
    return $results;
  
}   



function sns_display_post_action(){
    $facebookID = get_option( 'facebook_page_id' );
    $instagramID =  get_option( 'instagram_profile_id'  );
    $instagramName = get_option('instagram_profile_name');
    $optionArray = array(
  
      CURLOPT_RETURNTRANSFER   => TRUE,
     CURLOPT_TIMEOUT          => 10
  
    );
  $data = [];
  $access_token = get_option('access_token');
  $limitpost = get_option( 'post_count_number' );

 
 $data1 =  "https://graph.facebook.com/v14.0/$instagramID?fields=business_discovery.username($instagramName){id,name,profile_picture_url,media.limit($limitpost){id,owner,username,media_type,permalink,caption,timestamp,media_url,children{media_url}}}&access_token=$access_token";
 $data2 =  "https://graph.facebook.com/v14.0/$facebookID?fields=id,about,name,picture{url},posts.limit($limitpost){id,created_time,message,permalink_url,attachments{media_type,type,media,url,subattachments,unshimmed_url,description},full_picture}&access_token=$access_token";
 
  //Create an array of your urls.
  $urlArray = array(
  
     $data1,
     $data2
  
  );


  $nThreads = 2;
  
  //To use run the function.
  $results = multi_thread_curl($urlArray, $optionArray, $nThreads);
  echo $results;

}

add_action( 'wp_ajax_sns_post_action', 'sns_display_post_action');
add_action( 'wp_ajax_nopriv_sns_post_action', 'sns_display_post_action');

the javascript fetch code

  let params =  new FormData();
params.append("action", sns_show_options.action);
params.append("nonce", sns_show_options.nonce);

    fetch(sns_show_options.api,{
    headers,
    body:params,
  } )
   .then(respon => respon.json())

   .then(res =>{
        console.log(res)
  
   })

CodePudding user response:

$results is an array that you build up in multi_thread_curl, which you cannot echo outright, so your ajax is seeing Array. Use echo json_encode($results); instead.

CodePudding user response:

Echoing $result means the data is not encoded as a json object thereby returning an array. You should encode your result using json_encode($result) also exit after echo else it may introduce an unnecessary value 0;

  • Related