0

I'm trying to send a JSON object from PHP to my Javascript code. I'm new to PHP, so I'm running into some troubles achieving this. As a note, all of my HTML, PHP, and javascript code are contained within a single PHP file. I looking for solutions that don't use AJAX or Jquery, so I've been trying the json_encode method. Unfortunately, while my code will compile, my javascript object seems to be NULL after I parse it.

I have tried json_encode from a variable in javascript and, while there are no errors, it still returns a NULL object. I also have tried to send it to a hidden form field and retrieve it from there using DOM, to little success. I suspect that maybe my PHP code is simply not running after form submission, but I don't know if that is the root of my issue or my syntax is incorrect when attempting to transfer a php object to my javascript code.

<?php
    $street = $city = $state = $location = $url = $lat = $lon = "";
    $geolocation = $coords = $temp = $details = null;
    $temparray = array();

    if ($_SERVER["REQUEST_METHOD"] == "POST") {
            if(isset($_POST['location']) && $_POST['location'] == 'Yes'){
                $geolocation = json_decode($_POST["geolocation"]);
                $lat = $geolocation->lat;
                $lon = $geolocation->lng;
                $details = find_forecast($lat, $lon);
            }else{
                $street = $_POST["street"];
                $city = $_POST["city"];
                $state = $_POST["state"];
                $temparray = find_coords($street, $city, $state);
                $lat = $temparray[0];
                $lon = $temparray[1];   
                $details = find_forecast($lat, $lon);
            }
    }
?>

I didn't include the functions in my php code above because I know that the php code itself works (I tested in a separate environment with hardcoded values).

<script type="text/javascript">
     document.getElementById('theform').addEventListener('submit', 
     function(evt){
            evt.preventDefault();
            var stuff = "<?php echo json_encode($details); ?>"; //tried 2 ways 
            to achieve
            var arr = JSON.parse("<?php echo json_encode($details); ?>"); //2nd 
            way to test if it would work
            console.log(arr);
            document.getElementById("timezone").innerHTML = "<p 
            id='timezone'>" + arr.timezone + "</p>";
        })

This is my javscript code where I try to retrieve the JSON object, encode it, and parse it. Unfortunately, my "arr.timezone" results in a "undefined" value and my console.log(arr) results in "null".

<form id="theform" onSubmit="return checkInput()" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" target="testiframe">
            <h2><i>Weather Search</i></h2>
            <label for="street"><b>Street</b></label>
            <input id="street" name="street" type="text" value="">
            <div class="sub-entry">
            <input type="checkbox" id="location" name="location" value="Yes"> 
            Current Location
            </div>
            <br><br>
            <label for="city"><b>City</b></label>
            <input id="city" name="city" type="text" value="">
            <br><br>
            <label for="state"><b>State</b></label>
            <select name="state" id="state">
            <option value="state">State</option>
            <option value="line">----------------</option>
            <option value="AL">Alabama</option>
            <option value="AK">Alaska</option>
            </select>
            <br><br><br><br>
            <div class="button">
                <input id="search" name="Search" onclick="checkInput()" 
                type="submit" value="Search">
                <input id="clear" name ="clear" onclick="clearform()" 
                type="button" value="Clear">
            </div>
</form>
<div id= "blue" class="blue">
<p id="timezone"></p>
</div>

If it helps, this is part of my form. My file is named hello.php at the moment. Additionally, I have the target = testiframe (also an iframe tag at the bottom of my html) because I researched that it is a way for you page to not refresh after a form submission, as I wanted the user input values to remain after you submit. I tried removing this feature, and my javascript still didn't work properly though.

I've gotten no syntax errors. I should receive a JSON object from my find_forecast() and my data.timezone should not be undefined.Any help would be appreciated, as I've been stuck on this problem for awhile.

  • What is `data`? Should that be `stuff` or `arr`? – Barmar Nov 01 '19 at 00:14
  • @Barmar sorry I had taken the statement from a different function. Data should be arr, as I just updated it. – TheOneJellyFish Nov 01 '19 at 00:16
  • Possible duplicate of [How do I pass variables and data from PHP to JavaScript?](https://stackoverflow.com/questions/23740548/how-do-i-pass-variables-and-data-from-php-to-javascript) – miken32 Nov 04 '19 at 21:20

1 Answers1

0

json_encode() formats the result so it's a valid JavaScript literal. Don't put quotes in the JavaScript when you use <?php echo json_encode(...) ?>. You also don't need to call JSON.parse() (but if you do, you have to put it in single quotes, because double quotes are used in the JSON itself).

<script type="text/javascript">
document.getElementById('theform').addEventListener('submit', function(evt){
    evt.preventDefault();
    var stuff = <?php echo json_encode($details); ?>;
    console.log(stuff);
    document.getElementById("timezone").innerHTML = "<p id='timezone'>" + stuff.timezone + "</p>";
})
Barmar
  • 741,623
  • 53
  • 500
  • 612