Failed in json_encode ()

1

Good morning

I have a problem with a JavaScript variable that I'm trying to initialize with a PHP json_encode (), but then when I inspect the code of the page;
there is nothing inside the variable, that is, as if there was nothing inside the PHP variable, but I can attest that this variable is initialized and has data ... (in fact it is an array) Here I leave the code ...

if (isset($_SESSION['cesta']))
      {
$cesta = $_SESSION['cesta'];   // Aquí inicializo la variable de PHP que 
                               // viene cargada con los productos
      }

var cart = <?php echo json_encode($cesta); ?>; // variable que intento pasar 
                                               // a JavaSCript

Note that the JavaScript is embedded in a PHP document.

Is there anything I'm doing wrong?

    
asked by juan manuel maria hurtado 16.11.2017 в 13:24
source

1 answer

0

use the isset to validate only when the content is valid enter, you are assigning it outside the if, therefore an empty value may arrive ... evaluate with json:

<?php>
if (isset($_SESSION['cesta']))
{
    $cesta = $_SESSION['cesta'];   // inicializacion var de session en var local
    $CestaFinal = json_encode($cesta);//operas la var. sesion con json_encode
?>
<script type="text/javascript">
  // viene cargada con los productos
  var cart = <?=$CestaFinal;?>; // varible asignada en js desde php
  console.info(cart);//alerta de consola para validar contenido
</script>

<?php          
}// cierre del if de isset
// continuar tu logica del sistema....
?>

On the way you assign to cart you could do the operation of json_encode first and then the javascript assignment, in this way you avoid doing two operations at the same time that it can affect your code.

    
answered by 16.11.2017 в 15:18