PHP variable in JavaScript

-2

The simple and practical method I found here in the Stack to pass a PHP variable to a JS has worked fine so far. However, with a certain content it works only if I feed this PHP variable, but letting this variable receive that content through a query, no. (NOTE: The complete result set of the query has 13,700 characters.)

<?PHP 
    $consulta = mysql_query("SELECT MODELO FROM celular_banco");
    while($resultado=mysql_fetch_array($consulta))
    {
        $fracasso .= $resultado["MODELO"].',';
    }
  echo $fracasso; // LGA270.AVIVBK,LGA270.ACLRBK,
  $sucesso = "LGA270.AVIVBK,LGA270.ACLRBK,";

? >

<script>
var duvida = '<?PHP $sucesso;?>';
document.write(duvida); // OK!
</script>
FUNCIONA

<script>
var duvida = '<?PHP $fracasso;?>';
document.write(duvida); // SEM RESULTADO!
</script>
Não FUNCIONA
    
asked by anonymous 30.07.2018 / 15:32

3 answers

1

If your PHP delivers the HTML itself to the client, JavaScript does not even have to go into history. What you tried to do, even if you saw it in W3Scholls or right here on the site, is gambiarra.

What you can do is deliver the HTML ready. Something like:

<input list="modelos" />
<datalist id="modelos">
<?php
  $consulta = mysql_query("SELECT MODELO FROM celular_banco");

  while($resultado = mysql_fetch_array($consulta))
  {
    echo "<option value='{$resultado['MODELO']}'/>";
  }
?>
</datalist>

This will generate an HTML of the type for the client:

<input list="modelos" />
<datalist id="modelos">
  <option value="Foo"/>
  <option value="Bar"/>
  <option value="Baz"/>
  <option value="Acme"/>
  <option value="Zing"/>
</datalist>

That has the suggestion property as the user types.

What does the < / datalist >? tag serve

Another option you have is to feed your suggestion into the form asynchronously via the AJAX request, but if you already deliver the HTML ready with PHP, there is no need for a request.

    
30.07.2018 / 19:59
0

It seems that the $fracasso variable only exists within while , try:

<?PHP
    var $fracasso = '';
    $consulta = mysql_query("SELECT MODELO FROM celular_banco");
    while($resultado=mysql_fetch_array($consulta))
    {
        $fracasso .= $resultado["MODELO"].',';
    }
    // Não entendi a necessidade das linhas abaixo... 
    echo $fracasso; // LGA270.AVIVBK,LGA270.ACLRBK,
    $sucesso = "LGA270.AVIVBK,LGA270.ACLRBK,";
   ?>

JS (The JS part was missing, echo must be added to work correctly)

<script>
var duvida = '<?PHP echo $sucesso;?>';
document.write(duvida);

var duvida = '<?PHP echo $fracasso;?>';
document.write(duvida);
</script>
    
30.07.2018 / 16:03
-1

Try this:

<script>
$(document).ready(function(){
    var duvida = '<?PHP $sucesso;?>';
    document.write(duvida); 
    var duvida = '<?PHP $fracasso;?>';
    document.write(duvida);
}
</script>
    
30.07.2018 / 16:42