How to pass variables from PHP to jQuery? [closed]

-1

            

    

<?php 
$consulta = "SELECT idPais FROM pais";
$resultado = $conexion->query($consulta)or die("Error de busqueda o conexion");

while ($paisBuscado = $resultado->fetch_assoc() ) {
     $pais = utf8_encode($paisBuscado['idPais']);
     ?>
        <script>
            $(document).ready(cargar);
            function cargar(){
                var paisJq = "<?php echo $pais ?>";

$('#categoria').append('<option      value="paisJq">document.write("VariableJS = " + paisJq);</option>');

$('option',this).click(function(){
                    var valor=$(this).text();
                    alert(valor);
                });
            }
        </script>

<?php    
}

mysqli_free_result($resultado);
$conexion->close();
?>
    
asked by Gamez 09.03.2017 в 14:36
source

1 answer

2

To begin with, it does not make sense to use document.write within a append of jQuery . You have to use the + operator to concatenate text.

Second, it also makes no sense to make a function to add an option if the parameters are defined by echo .

I would do it in the following way:

<?php 
    include('configuracion/conexion.php'); 
?>
<script>
  jQuery('document').ready(function() {

  <?php 
    $consulta = "SELECT idPais FROM pais";
    $resultado = $conexion->query($consulta)or die("Error de busqueda o conexion");

    while ($paisBuscado = $resultado->fetch_assoc() ) {
       $pais = utf8_encode($paisBuscado['idPais']);
  ?>
       var paisJq= <?php echo $pais ?>;
       $('#categoria').append('<option value="'+ paisJq +'" >VariableJS = ' + paisJq +');</option>');
  <?php  
    }

    mysqli_free_result($resultado);
    $conexion->close();
  ?>

    $('option').click(function(){
      var valor=$(this).text();
      alert(valor);
    });

  });
</script>

Eye, that according to your question, #category is a DIV and not a SELECT.

    
answered by 09.03.2017 в 15:18