How to pass JSON response in PHP to Javascript

I have problems passing a JSON request from PHP to Javascript. I am sending a request to my Flask RESTful API and I'm recieving a JSON reponse (I believe). PHP:

$urlContents = file_get_contents("", false, $context);
$travelArray = json_decode($urlContents);

My Object looks like this:

stdClass Object
    [1] => stdClass Object
            [var1] => 
            [var2] => 
            [var3] => 763
            [var4] => 6:22:30
            [var5] => München
            [var6] => 58
            [var7] => Bremen
            [var8] => 239

    [2] => stdClass Object
            [var1] => 
            [var2] => 
            [var3] => 145
            [var4] => 3:12:23
            [var5] => München
            [var6] => 583
            [var7] => Bremen
            [var8] => 9


<script type="text/javascript">
            var response = JSON.parse('<?php echo $travelArray; ?>');
            if (response != null) {
            } else {

When I press F12 and look into sources it says:

var response = JSON.parse('<br />
<b>Recoverable fatal error</b>:  Object of class stdClass could not be converted to string in <b>/var/www/html/greenTravelWizard.php</b> on line <b>83</b><br />

I have tried several things like using $urlContents instead of $travelArray in the JavaScript part ([1]:, but I haven't figured out how to correctly pass the JSON to a correct JavaScript format.

Also when I haven't send the request via the form yet I get

Notice: Undefined variable: context in /var/www/html/greenTravelWizard.php on line 83

Warning: file_get_contents( failed to open stream: HTTP request failed! HTTP/1.0 405 METHOD NOT ALLOWED in /var/www/html/greenTravelWizard.php on line 83

1 answer

  • answered 2020-11-10 10:23 mplungjan

    You should not decode it unless you encode it before echoing

    You can likely just do

    var response = <?php echo $file_get_contents("", false, $context); ?>;

    If you have written a proxy, then you just need to do

    header("content-type: application/json"); 
    echo file_get_contents("", false, $context);

    and then use fetch to get it from your server