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
});
} );