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("http://192.168.2.201:5000/dataprovider", 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
        )
)

JavaScript

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

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]: https://i.stack.imgur.com/Tujy3.png), 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(192.168.2.201:5000/dataprovider): 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("http://192.168.2.201:5000/dataprovider", false, $context); ?>;
    

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

    <?php
    header("content-type: application/json"); 
    echo file_get_contents("http://192.168.2.201:5000/dataprovider", false, $context);
    ?>
    

    and then use fetch to get it from your server