0

I'm fairly new to PHP and JavaScript, so I was wondering if it was possible to use info taken from a .php into a JavaScript variable and use it outside of the script itself. Here is the particular case I'm tackling right now:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>LaWeaaa</title>
    <link rel="stylesheet" type="text/css" href="assets/css/login.css">
</head>
<body>
    <script type="text/javascript" src = pru.php>
        var img = '<?php echo $imagenes;?>'
    </script>
</body>
</html>

As it goes, I'd like to know if it is possible to use the variable 'img' outside of the script and if so, how to do it properly.

5
  • 1
    What do you mean, outside of the script? Since it's echoed into the <script>, you can have the Javascript use it as desired, including for manipulating HTML Commented May 20, 2018 at 23:41
  • The src = pru.php won't work. May we see that file (or a sample of it) in your question? Does it just contain data or does it run code (and set variables)? Commented May 20, 2018 at 23:46
  • 1
    You can just do echo it out like you do in the javascript. <img src="<?php echo $imagenes;?>"> Commented May 20, 2018 at 23:46
  • Think of PHP files as server-side scripts which output whole other files (like HTML or JS). For example, you could use something like: <script type='text/javascript' src='myPhpFile.php'></script> where myPhpFile.php can use whatever variables and output them however you want, and then return a valid JavaScript file to process when your HTML file is loaded in the browser. Commented May 20, 2018 at 23:49
  • @halfer pru is just a test .php, it only says <?php $imagenes = "genial"; ?> I just want to use the value of img in the body, not the script. Since I'm trying to show it in the same html page. Commented May 21, 2018 at 0:01

1 Answer 1

1

You could do something like this. First the PHP, arranged to return a value (or set of values):

<?php

return [
    'foo' => "genial",
    // Any other values here...
];

And the JS:

<script type="text/javascript">
    var data = <?php echo json_encode(require('pru.php')) ?>,
        img  = data['foo'];
</script>

The require() fetches the data returned by the script, and then the data is encoded in a string format that is native to JavaScript.

Of course, you can just return a bare string from the PHP script, but I've shown how to return an array, in case your actual needs are more complex.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.