1

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);

2 Answers 2

1

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();

Sign up to request clarification or add additional context in comments.

Comments

0

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.