1

So I have invoked an API using PHP with the following code:

$url_get_fc = 'http://apiurlhere'; 

//Send the request
$response_fc = curl_exec($ch_fc);
curl_close($ch_fc);

//Check for errors
if($response_fc === FALSE){
 die(curl_error($ch_fc));
}
// Decode the response
$responseData_fc = json_decode($response_fc, TRUE);

// sessionStorage

sessionStorage.setItem(responseData_fc);

console.log(set);

Now, I am trying to store the json file being passed by the API inside the sessionStorage on the browser. Is this possible? Not so sure how to store it in the browser since I know sessionStoage is javascript? Hope someone could enlighten me

B. Magic
  • 23
  • 2

1 Answers1

2

To use the SessionStorage on the browser you must use javascript that is a language executed on the client side (browser), php is a language that is going to be executed on the server side, so is not valid to do what you need.

To fix your example you can:

  1. Use php to call the API and send the result to the client assigned to one variable, so it can be read from javascript ans stored in the SessionStorage.
  2. Use javascript to perform the call to the API, using this way you are going to have less performance problems in the future.

I also recommend you to read something about client side/server side differences as was pointed by @jon-stirling.

Using your code, one example for case 1 could be:

$url_get_fc = 'http://apiurlhere'; 

//Send the request
$response_fc = curl_exec($ch_fc);
curl_close($ch_fc);

//Check for errors
if($response_fc === FALSE){
 die(curl_error($ch_fc));
}
// Decode the response
$responseData_fc = json_decode($response_fc, TRUE);

// sessionStorage

echo '
<html><head>
<script type="text/javascript">
    alert("'.$responseData_fc.'");
</script>
</head><body></body></html>';
Óscar Andreu
  • 1,630
  • 13
  • 32
  • Can I do the number 1 using just one PHP file? I was hoping I could insert a javascript snippet inside my PHP code? Sorry, I am not so sure how to move forward :( – B. Magic Sep 10 '18 at 10:41
  • Answer updated, why the way, if the answer is right, please mark it as right answer. – Óscar Andreu Sep 10 '18 at 11:36