Home > Back-end >  Can I set a javascript variable to be a string that contains the output from php code?
Can I set a javascript variable to be a string that contains the output from php code?

Time:04-15

I am trying to set a javascript variable to be equal to the output of php code:

var name = '<?php global $email; echo json_encode(passthru("python Backend/User/getName.py $email"));?>';

When this runs, it returns the correct value, but it also attaches a null value to it:

var name = 'name
null';

This causes the code to take the value as null and not as the name returned.

CodePudding user response:

As stated, passthru returns null on success and false on failure.

What you are looking to get is the content of the file so a simple way to do it is to just use output buffering.

You can have a simple function to return the value of your script like so:

<?php
function getPassthruValue(string $command)
{
    ob_start();
    passthru($command);
    $returnValue = ob_get_contents();
    ob_end_clean();
    return $returnValue;
}
global $email;
$value = getPassthruValue("python Backend/User/getName.py $email");
?>
<script>
    var passthruValue = "<?= $value ?>"
</script>

<?= === <?php echo just incase you didn't know what the shorthand annotation means.

This will grab the value of your python script and then set it to a js value.

This will return an empty string on failure so you may need to put some exception handling in depending on your needs.

  • Related