Receive a string from a PHP array for a Javascript variable?

Asked

Viewed 247 times

0

I have a PHP array with a certain string, Ex.:

 $matriz[2][2] = "texto"`.

Hence I want to pass this matrix to a Javascript variable.

Ex.:

`var v_php = "<?php echo $matriz[2][2]; ?>";`

When I display the content on the screen, everything is ok. Ex.:

document.write(v_php);

But when I make a condition/comparison with another JS variable coming from an HTML INPUT, then the result is always false, regardless of what is inside each string.

Complete code:

    <?php $matriz[2][2] = "texto"; ?>

<input type="text"   id="id_field" value=""/>
<input type="button" id="corrige"  value="VERIFICAR" onclick="funcButton()" />

    <script type="text/javascript">

      function funcButton(){

        var v_js  = document.getElementById("id_field").value;
        var v_php = "<?php echo $matriz[2][2]; ?>" ;

        // Verificando as strings
        document.write(v_js);
        document.write(v_php );

        if ( v_js == v_php ){
          alert('Variáveis Idênticas.');
        }else{ 
               alert('Variáveis Diferentes');
             } 
      }
    </script>
  • I tested the code and it worked, if you write "text" it makes the Alert 'Identical Variables.'

  • There really is no error. The code worked here too.

  • Actually, I actually tried to show an example to hack the code, but the problem is that this Matrix, comes from a database select and soon after it is randomized with "shuffle". Only after this data is assigned to JS variable. Due to all this, there must be some error in the conversion.

1 answer

0


Pass the array as json with the function json_encode:

<script type="text/javascript">
// passando a matriz do php para o javascript
var matriz = <?php echo json_encode( $matriz ) ?>;

// acessando a matriz no JavaScript
console.log( matriz[2][2] ); // texto
</script>

  • 1

    Perfect my dear, with json_encode worked perfectly! I will study a little about it as I would like to understand the pq to work with it. Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.