Receiving a string from a PHP array to a JavaScript variable?

0

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

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

Then I want to pass this array to a JavaScript variable.

Eg:

'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's 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>
    
asked by anonymous 28.07.2016 / 05:17

1 answer

0

Pass the array as json with the json_encode function:

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

// acessando a matriz no JavaScript     

28.07.2016 / 20:48