Reputation: 2783
I am working on a webpage where user will input the number which will be used as a query parameter to API call & need to display the response in webpage. I am running this local mac with php server running on same mac using below command
php -S localhost:8080 -t /Users/demouser/my_website
I have verified that curl is enabled using phpinfo().
I have below function in HTML file which will be called on tap of button using javascript.
function performRequest(todoid) {
$.ajax({
url:"api_call.php",
type: "GET",
data: { todoid: todoid },
success:function(result){
console.log("JS result"+result);
}
});
}
My PHP file looks like below
<?php
if (isset($_GET['todoid']))
{
callExternalAPI($_GET['todoid']);
}
function callExternalAPI($todoid)
{
$result = callAPI("https://jsonplaceholder.typicode.com/todos/".$todoid);
print_r("Result from URL".$result);
$info = json_decode($result, true);
echo("Info from API".$info);
}
function callAPI($url)
{
$curlObj = curl_init();
curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curlObj, CURLOPT_ENCODING, "identity");
curl_setopt($curlObj, CURLOPT_URL, $url);
if (!$result = curl_exec($curlObj))
{
echo "Failed to perform request".curl_error($curlObj);
}
curl_close($curlObj);
return $result;
}
?>
But in Ajax success callback, I am getting
JS resultResult from URLhttps://jsonplaceholder.typicode.com/todos/1Info from API
When I hit the same API in browser or postman, I am getting the correct json response. I don't really understand what I am missing here. Can anyone please help me understand the issue? Thanks
Upvotes: 0
Views: 1839
Reputation: 33804
Perhaps the following might help - as the endpoint is https you ought to have additional options set in the curl request function to deal with SSL. The curl function below is a simplified version of something I use frequently
<?php
/* https://stackoverflow.com/questions/55339967/unable-to-get-the-json-response-from-api-using-curl-in-php */
/* jsonplaceholder.typicode.com api experiments */
if( isset( $_GET['todoid'] ) ){
$id=filter_input( INPUT_GET, 'todoid', FILTER_SANITIZE_NUMBER_INT );
/* utility to quickly display data in readable fashion */
function pre( $data=false, $header=false, $tag='h1' ){
if( $data ){
$title = $header ? sprintf('<'.$tag.'>%s</'.$tag.'>',$header) : '';
printf('%s<pre>%s</pre>',$title,print_r($data,1));
}
}
/* basic curl request helper */
function curl( $url ){
/* set an appropriate path to YOUR cacert.pem file */
$cacert='c:/wwwroot/cacert.pem';
$curl=curl_init();
if( parse_url( $url,PHP_URL_SCHEME )=='https' ){
curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, true );
curl_setopt( $curl, CURLOPT_SSL_VERIFYHOST, 2 );
curl_setopt( $curl, CURLOPT_CAINFO, $cacert );
}
curl_setopt( $curl, CURLOPT_URL,trim( $url ) );
curl_setopt( $curl, CURLOPT_AUTOREFERER, true );
curl_setopt( $curl, CURLOPT_FOLLOWLOCATION, true );
curl_setopt( $curl, CURLOPT_FAILONERROR, true );
curl_setopt( $curl, CURLOPT_HEADER, false );
curl_setopt( $curl, CURLINFO_HEADER_OUT, false );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36' );
curl_setopt( $curl, CURLOPT_MAXREDIRS, 10 );
curl_setopt( $curl, CURLOPT_ENCODING, '' );
$res=(object)array(
'response' => curl_exec( $curl ),
'info' => (object)curl_getinfo( $curl ),
'errors' => curl_error( $curl )
);
curl_close( $curl );
return $res;
}
function callapi( $id ){
$url=sprintf( 'https://jsonplaceholder.typicode.com/todos/%s',$id );
return curl( $url );
}
/* call the api */
$res = callapi( $id );
/* process response data */
if( $res && $res->info->http_code==200 ) {
/* to debug */
pre( $res->response, 'Response data' );
/* live */
#exit( $res->response );
}
}
?>
Example output:
{
"userId": 2,
"id": 23,
"title": "et itaque necessitatibus maxime molestiae qui quas velit",
"completed": false
}
Upvotes: 1
Reputation: 8338
Ok first in your ajax call add:
url:"api_call.php",
type: "GET",
data: { todoid: todoid },
dataType : "json",
After that you have an error in your php. You try to echo an array.
$info = json_decode($result, true); // this line will get you an array
print_r($info); // this is the way to print the array. Echo is used for strings
Just a small suggestion i don't see any reason to return a json and an array with the same data in the ajax success. Return your json only and handle the data with javascript.
What you can do is simple use this line of code that you already have:
echo("Result from URL".$result); // you can echo that one since it's just a json string
Upvotes: 0