Seth Alexander
Seth Alexander

Reputation: 11

How to pass data JSON string from PHP to external javascript

I have a php page that loads a JSON object string from a text file. I want to send the object string to an external javascript file which will eventually use it to update html displayed from the php page. Unfortunately I've had trouble getting the string to the external javascript.

I've been trying to follow the approach outlined by Afzal Ahmad here Pass Php Arrays to External Javascript File but I get no results

The php:

<?php

session_start();
echo 'Hello ' . $_SESSION['first'] . '<br>';
loadUserData();
displayPage();

function loadUserData(){
        $userString = 'userdata/'.$_SESSION['email'].'.txt';
    echo $userString;
    $user = file_get_contents($userString);
}

function displayPage(){
/*html stuff here*/
}

?>
<script type="text/javascript">var userObj = <?php echo json_encode($user); ?>;</script>
<script type="text/javascript" src="scripts/index.js"></script>

The javascript:

console.log(userObj);

Upvotes: 1

Views: 269

Answers (2)

Maxime Launois
Maxime Launois

Reputation: 958

That happens because you haven't declared $user in the function loadUserData as a global variable.

To fix the issue, you'll have to use the global keyword:

function loadUserData() {
    global $user;

    $userString = 'userdata/'.$_SESSION['email'].'.txt';
    echo $userString;
    $user = file_get_contents($userString);
}

Upvotes: 0

Samuel Aiala Ferreira
Samuel Aiala Ferreira

Reputation: 694

Your loadUserData function isn't returning anything.

You should remove the echo $userString; and add a return $user after the file_get_contents.

And you should change the loadUserData(); to $user = loadUserData();

Upvotes: 1

Related Questions