Pass JavaScript variable to PHP

1

Good afternoon, classmates, I have a problem, I hope you can support me, I need to pass data stored in a variable using JavaScript to PHP, how can I do that? I came up with the following but I see that you can not:

  <body>
    <script>
            var miVariable = "Hola Mundo";                    
    </script> 
<?php
$datos = "<script>miVariable</script>";
echo $datos;
?>
    </body>

Thank you in advance to everyone.

P. D. Use Windows 7 and PHP 7.

    
asked by Carlos Daniel Zárate Ramírez 22.06.2018 в 21:58
source

3 answers

1

My solution would be to place your value in a text box using javascript and followed by using POST php to take the value.

javascript_a_php.php

<html>
<form action="tu_action.php" method="POST">
<input type="text" name="caja_valor" id="caja_valor" value="">
<input type="submit" value="Guardar">
</form>
</html>

<script>
let valor = 4;
document.getElementById("caja_valor").value = valor;
</script>

tu_action.php

<?php
$valor = $_POST["caja_valor"];
echo $valor; 
// el valor
?>

Notes

  • The ID in a field is used so that javascript can access the Element values.

  • The NAME is used so that PHP can get the data

  • The code JAVASCRIPT is already on your side as loading the values, if automatically, with a button, any event among others.

  • The code PHP will be activated when you press the button.

  • answered by 22.06.2018 / 22:11
    source
    0

    try using var mivariable = "<?php $mivar = "holamundo" ?>"; declare your variable first in php, then from javascript you assign it with another value.

      

    php

    echo $mivar;
    
        
    answered by 22.06.2018 в 22:05
    -2

    I would do it like this:

    <?php
    $captura='';
    if(!isset($_GET['variable'])){
        $captura='No';
    }
    ?>
    <body onload="parametro(<?php echo $captura; ?>) ">
    
    <script>
    function parametro(captura){
        var miVariable = "Hola Mundo"; 
        if(captura=='No'){
            window.location="esta_pagina.php?variable=miVariable";
        }    
    }                   
    </script> 
    <?php
        $datos = $_GET['variable'];
        echo $datos;
    ?>
    </body>
    

    I hope and serve you.

        
    answered by 12.12.2018 в 02:12