Pass variables from PHP to jQuery and vice versa

0

What is the best way?

I've seen this question where variables are passed in this way:

<?php
 $row= "pantalla";
?>

<script type="text/javascript">
  var row = '<?php echo $row;?>'
</script>

Also applicable to arrays

<?php
   $row= array( "pantalla","chip","flex" );
?>

<script type="text/javascript">
    var row = [ <?php echo implode("','",$row);?> ]
</script>

I have also seen that it can be done with json_encode($row) but I do not know how to function and in all the sites that I have searched the explanations are liosa.

If I have an array $row[] , when doing json_encode() how do I use them in jquery? That is to put it in a variable jquery and use it.

I EDIT THE QUESTION TO ADD MORE DATA:

I intend to do an autocomplete from the database.

I have a two-dimensional array named $data and I want to send it to jquery to use its values as options for autocomplete.

<?php
    $i=0;
    $query = $db->query("SELECT * FROM piezas" );
    while ($row = $query->fetch_assoc()) {
        $data[$i]['id'] = $row['id'];
        $data[$i]['codigo'] = $row['codigo'];
        $data[$i]['nombre'] = $row['nombre'];
        $i++;
    }
    json_encode($data);
    ?>
    <script type="text/javascript">
        $( function() {
        var autocomlpetePiezas = <?php echo $json_encode($data) ?>
            $( "#piezas" ).autocomplete({
                source: autocomlpetePiezas
            });
        });
    </script>

EDITO original code of the autocomplete of jqueryUI:

$( function() {
    var availableTags = [
      "ActionScript",
      "AppleScript",
      "Asp",
      "BASIC",
      "C",
      "C++",
      "Clojure",
      "COBOL",
      "ColdFusion",
      "Erlang",
      "Fortran",
      "Groovy",
      "Haskell",
      "Java",
      "JavaScript",
      "Lisp",
      "Perl",
      "PHP",
      "Python",
      "Ruby",
      "Scala",
      "Scheme"
    ];
    $( "#tags" ).autocomplete({
      source: availableTags
    });
  } );
    
asked by Pavlo B. 18.01.2017 в 10:53
source

2 answers

1

To generate in a PHP script a matrix / object to be used in JavaScript you can use json_encode() as follows:

<?php
$prueba = new stdClass();
$prueba->matriz = [
  'indice1' => 'valor1',
  'indice2' => 'valor2',
];
$prueba->propiedad = 'valor de propiedad';
?><script type="text/javascript">
console.log(<?= json_encode($prueba,
    JSON_HEX_QUOT | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS
) ?>);
</script>

With json_encode() you encode the data in JSON to be used by JavaScript.

Although the security of the function json_encode() is usually enough, a bad implementation in the browser or changing the default mode could be a problem, so it is advisable to use the options JSON_HEX_QUOT | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS . Without these options </script> would be converted to <\/script> and with them it would become \u003C\/script\u003E .

In my code I used a class with an array and a property so that you have a fairly complete example.

I edit to update my response to your edition:

<?php
    $query = $db->query("SELECT * FROM piezas" );
    $data = [];
    while ($row = $query->fetch_assoc()) {
        /* Agregamos únicamente los nombres */
        $data[] = $row['nombre'];
    }
?>
<script type="text/javascript">
  $( function() {
    var autocompletePiezas = <?= json_encode($data,
      JSON_HEX_QUOT | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS
    ) ?>;
    $( "#piezas" ).autocomplete({
      source: autocompletePiezas
    });
  });
</script>
    
answered by 18.01.2017 / 11:18
source
1

In my humble opinion, would not it be better to use AJAX?

You would have your script:

<script>
        $.ajax({
            url: 'controller.php', //Tu archivo donde estará tu consulta
            type: 'POST', 
            dataType: 'json',
        })
        .done(function(data) {
            console.log(data); //Imprime tu arreglo, observa la estructura
        })
        .fail(function() {
            console.log("Error al cargar el arreglo");
        });
</script>

Your php file:

<?php
    $array = array(
                0=>array("id"=>"1","codigo"=>"a","nombre"=>"user1"),
                1=>array("id"=>"2","codigo"=>"b","nombre"=>"user2"),
                2=>array("id"=>"3","codigo"=>"c","nombre"=>"user3"));


    echo json_encode($array);
?>

Greetings!

    
answered by 19.01.2017 в 21:06