Run PHP code inside Javascript

0

They could help me with a problem:

I want to execute PHP code inside Javascript .

<html>
<head></head>
<body>
    <script type="text/javascript">
        <?php echo "hola como estan"; ?>);
    </script>
</body>
</html>

The html output:

<html>
<head></head>
<body>
    <script type="text/javascript">
        hola como estan <-- marcado en rojo en el inspector del navegador
    </script>
</body>
</html>

The error in the browser console:

  

Uncaught SyntaxError: Unexpected identifier

    
asked by Javier 26.04.2018 в 19:59
source

2 answers

1

I think there is a conceptual error when it comes to structuring the task you want to do.

Really PHP is not executed within Javascript , but Javascript will make use of what PHP prints within its labels or functions. Since PHP is a server language, it will be executed before Javascript .

Basic to be understood, the order in which they are executed:

1st PHP (server)
2nd HTML (browser)
3rd Javascript (browser)

Then the flow would go like this:

1.- What result do we want to achieve?

<html>
<head></head>
<body>
    <script>
       alert("hola como estan"); 
    </script>
</body>
</html>

2.- What part of that result will you manage PHP ?

hola como estan

3.- How does PHP print this text inside html ?

<?php echo "hola como estan"; ?>

4.- How do you get everything going?

<html>
<head></head>
<body>
    <script>
       alert("<?php echo "hola como estan"; ?>");
       //    ^                                ^
       //   (1)                              (2)
    </script>
</body>
</html>
  

Beware of the syntax, the Javascript quotes must be maintained.

A simple example:

<?php
// varios textos en un array
$txt = array(
    "Hola como estan",
    "Hola que tal va",
    "Hola ke ase XD",
);
// desordena el contenido del array
shuffle($txt);
?>

<html>
<head></head>
<body>
    <script>
       // cada vez que recarga el navegador
       // debería lanzar el texto de forma 
       // aleatoria
       alert("<?php echo $txt[0]; ?>"); 
    </script>
</body>
</html>
    
answered by 26.04.2018 в 21:00
0

Just as you have it is a syntax error. If you want to write something you can use the console like this:

<?php echo "console.log('hola como estan');"

Or an alert like that:

<?php echo "alert('hola como estan');"
    
answered by 26.04.2018 в 20:04