Bring php variable in an xmlhttp function

1

I am working with html, php, javascript, postgres. I have a form that contains a combo, a button and a panel.

The operation of the form basically is: choose a type of animal, press the filter button and the panel displays a table with the sql query that shows the number of animals of that type that are in that location.

I have the following code:

HTML code

  

COMPLETE HTML CODE

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta charset="UTF-8">
<link rel='stylesheet prefetch' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css'>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="css/main.css"/>

<?php
session_start();

$user = $_SESSION['varname'];

if (isset($_SESSION['varname'])) {

} 
else {
            echo "Esta pagina es solo para usuarios registrados.<br>";
            header( "Location: auth4.php" );
            exit;
}
//SI SE AGOTO EL TIEMPO DE ESPERA ASIGNADO EN TIME... 
$now = time();
if($now > $_SESSION['expire']) {
            echo "<script> alert('Su tiempo de sessión ha expirado.'); </script>";
            session_destroy();
            header( "Location: login.php" );
}

$host = "localhost";
$db = "animales";
$user = "postgres";
$pw = "admin";
$port = "5432";

$packedString = "host=" . $host . " dbname=" . $db . " user=" . $user . " password=" . $pw . " port=" . $port;


$dbconn = pg_connect("$packedString")or die('Could not connect: ' . pg_last_error());

if($user){}
?>

<head>
<title>Formulario animales</title>
</head>
<body>

    <div id="header">
          <div class="headerBackground"></div>
    </div>

    <div id="content">
        <form type="submit" method="post" role="form-horizontal" id="form-fil">
            <div class="form-group">

                    <div class="col-sm-2" id="tittle">
                        <h1><b>FORMULARIO ANIMALES POR LOCALIDAD </b> <br><b>Clave localidad:  <?php $idLocalidad = $_GET['id_Localidad']; echo $idLocalidad?> </b></h1>
                        </div>

                        <div class="col-sm-3">
                        <label for="sel3">Animales: </label>

                            <select class="form-control" name="selAnimal" id="selAnimal" >
                                <?php

                            $query="select nb_animal from animales;";
                            $result = pg_query($query) or die('Query failed: ' . pg_last_error());
                            $rows = pg_num_rows ($result);
                            $i = pg_num_fields($result);


                                while ($line = pg_fetch_array($result)){
                                        if ($line[0] <> "") {
                                            echo "<option value='$line[0]' >$line[1]</option>";
                                        }
                                        else{
                                            echo"<option >&nbsp;</option>"; 
                                        }
                                }
                            ?>

                            </select>

                        </div>

                        <div class="col-sm-2">
                                <button type="button" class="btn btn-default" name="filtrar" value="Filtrar" id="buttonFiltro" onClick="showTableAnimales();">Filtrar </button>
                        </div>
                <div class="col-sm-2" id="diccionario">
                    <script src="https://code.jquery.com/jquery-1.11.1.min.js"></script> 
                    <script src="https://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>


                    <div class="table-responsive" id="panel-oculto" style="display:none;" class"col-sm-2">
                        <div id="theTableDiccionario"></div>

                </div>

                    <a href="#" id="alternar-panel-oculto" onClick="showTableDic()">Consultar Variable</a><i class="glyphicon glyphicon-info-sign fa-1x" aria-hidden="true" style="color:blue"></i>
            </div>                          

  </form>

<form method="post" class="form-horizontal">
    <div class="panel">

            <div id="theTableAnimal"><b>Filtre el animal del cual desea consultar información</b></div>

    </div>



</body>
<script>
//------------Filtrar animal

function showTableanimal() {
            r=document.getElementById("selAnimal").value;//almacena la respuesta del list (el tipo de rezago)
            var idLocalidad = <?php echo $_GET['id_Localidad']; ?>
        console.log("Animal" + r);

  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else { // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function() {
    if (this.readyState==4 && this.status==200) {
      document.getElementById("theTableAnimales").innerHTML=this.responseText;


    }
  }
  xmlhttp.open("GET","includes/getTablePorApoyar.php?r="+r+"&id_localidad="+idLocalidad,true);
  xmlhttp.send();
}



function showTableDic() {//Muestra informacion respecto a la variable que se elija en el combo
            r=document.getElementById("selAnimal").value;

        console.log("animal" + r);

  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else { // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function() {
    if (this.readyState==4 && this.status==200) {
      document.getElementById("theTableDiccionario").innerHTML=this.responseText;

    }
  }
  xmlhttp.open("POST","includes/getTableDiccionario.php?r="+r,true);
  //console.log("Valor de Ageb #2 = " + q);
  xmlhttp.send();
}
</script>
<script type="text/javascript">

<!--
// jQuery
$(document).ready(function(){ 

    $('#alternar-panel-oculto').toggle( 

        /* 
            Primer click.
            Función que descubre un panel oculto
            y cambia el texto del botón.
        */
        function(e){ 
            $('#panel-oculto').slideDown();
            $(this).text('Consultar otra variable');
            e.preventDefault();
        }, // Separamos las dos funciones con una coma

        /* 
            Segundo click.
            Función que oculta el panel
            y vuelve a cambiar el texto del botón.
        */
        function(e){ 
            $('#panel-oculto').slideUp();
            $(this).text('Consultar Variable');
            e.preventDefault();
        }
     );
 });
</script>
</html>

Script Code

function showTableAnimales() {
            r=document.getElementById("selAnimal").value;//almacena la respuesta del list (el tipo de animal)

        console.log("ANIMALES" + r);

  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else { // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function() {
    if (this.readyState==4 && this.status==200) {
      document.getElementById("theTableApoyados").innerHTML=this.responseText;


    }
  }
  xmlhttp.open("POST","includes/getTableAnimales.php?r="+r,true);

  xmlhttp.send();
}

getTableanimales.php *

  

ADD MY $ _GET

*

    <?php
    die(var_dump($_GET));
    $host = "localhost";
    $db = "animales";
    $user = "postgres";
    $pw = "admin";
    $port = "5432";

    $packedString = "host=" . $host . " dbname=" . $db . " user=" . $user . " password=" . $pw . " port=" . $port;


    $dbconn = pg_connect($packedString)or die('Could not connect: ' . pg_last_error());
    session_start();

    $r = intval($_GET['r']);
$idLocalidad=['id_localidad'];
        $query="select count (animal)
                from animales a, localidades l
                where a.c_animal in($r) and id_localidad = '$idLocalidad' //esto es lo que necesito PERO NO SE COMO TRAER AQUÍ MI VARIABLE $ID_LOCALIDAD
                group by a.animal;";

        $result = pg_query($query) or die('Query failed: ' . pg_last_error());
        $rows = pg_num_rows ($result);
        $i = pg_num_fields($result);

        echo "<table class='table table-fixed' border=1> <thead><tr> ";
        for($j=0; $j<$i; $j++){
                $fieldname=pg_field_name($result, $j);
                echo "<th>".strtoupper($fieldname)."</th>"; //columns

        }
        echo "</tr> </thead>"
        ?>



        <?php 
            echo "<tbody>";
            while ($line = pg_fetch_array($result)){
                echo "<tr>"; 
                for($j=0; $j<$i; $j++){
                        if ($line[$j] <> "") {
                                echo "<td>$line[$j]</td>";

                        }
                        else{
                                echo"<td >&nbsp;</td>"; 
                        }
                }   
                echo "</tr>";   
        } 
        echo "</tbody>";
        echo "</table>";

    ?>

What I need is to bring my variable $ idLocalidad and its value 'idLocalidad' and use it in my query of the page getTableAnimales but the truth I do not know how to do it, I hope you can help me, thanks

    
asked by IndiraRivas 13.03.2018 в 19:09
source

1 answer

2

You can print the value of your PHP variable in the showTableAnimal function in the following way to get the value of the locality id and use it in your JavaScript code.

function showTableAnimales() 
{
    var id_localidad = <?php echo $_GET['idLocalidad']; ?>
    //resto de tu codigo
}

Greetings!

EDIT

Response to the comment: I do not usually use flat javascript to make this type of calls but it should work:

function showTableAnimales() 
{
    var id_localidad = <?php echo $_GET['idLocalidad']; ?>
    //resto de tu codigo

    xmlhttp.open("GET","includes/getTableAnimales.php?r="+r+"&idlocalidad="+id_localidad,true);
    xmlhttp.send();
}

Then in your php you can access it in this way:

$_GET['idlocalidad'];

UPDATE

I was reviewing a bit the code that you updated in your question. and I have noticed that it has enough errors, it is not well organized, for example you put code that goes in the head outside of it, you have to close tags, include javascript libraries where they do not go, etc.

I think you should start there, to understand a bit the functioning of HTML and how and where to add libraries.

As a help, I'm going to paste a part of your code (it's not complete), reorganized a bit to guide you and since I see that in certain areas you use Jquery, I rewrote the showTableAnimal function with jquery as well so that it serves as orientation.

luck in your fight friend, may the force accompany you.

<?php
session_start();
$user = $_SESSION['varname'];

if (isset($_SESSION['varname'])) {

} 
else {
    echo "Esta pagina es solo para usuarios registrados.<br>";
    header( "Location: auth4.php" );
    exit;
}
//SI SE AGOTO EL TIEMPO DE ESPERA ASIGNADO EN TIME... 
$now = time();
if($now > $_SESSION['expire']) {
    echo "<script> alert('Su tiempo de sessión ha expirado.'); </script>";
    session_destroy();
    header( "Location: login.php" );
}

$host = "localhost";
$db = "animales";
$user = "postgres";
$pw = "admin";
$port = "5432";

$packedString = "host=" . $host . " dbname=" . $db . " user=" . $user . " password=" . $pw . " port=" . $port;

$dbconn = pg_connect("$packedString")or die('Could not connect: ' . pg_last_error());

if($user){}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
    <title>Formulario animales</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
    <meta charset="UTF-8">
    <link rel='stylesheet prefetch' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css'>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="css/main.css"/>
</head>
<body>
    <div id="header">
          <div class="headerBackground"></div>
    </div>
    <div id="content">
        <form type="submit" method="post" role="form-horizontal" id="form-fil">
            <div class="col-sm-2" id="tittle">
                <h1><b>FORMULARIO ANIMALES POR LOCALIDAD </b> <br><b>Clave localidad:  <?php $idLocalidad = $_GET['id_Localidad']; echo $idLocalidad?> </b></h1>
            </div>¿
            <div class="col-sm-3">
                <div class="form-group">
                    <label for="sel3">Animales: </label>
                    <select class="form-control" name="selAnimal" id="selAnimal" >
                        <?php

                            $query="select nb_animal from animales;";
                            $result = pg_query($query) or die('Query failed: ' . pg_last_error());
                            $rows = pg_num_rows ($result);
                            $i = pg_num_fields($result);

                            while ($line = pg_fetch_array($result)){
                                if ($line[0] <> "") {
                                    echo "<option value='$line[0]' >$line[1]</option>";
                                }
                                else{
                                    echo"<option >&nbsp;</option>"; 
                                }
                            }
                        ?>
                    </select>
                </div>
            </div>
            <div class="col-sm-2">
                <button type="button" class="btn btn-default" name="filtrar" value="Filtrar" id="buttonFiltro">Filtrar </button>
            </div>
            <div class="col-sm-2" id="diccionario">
                <div class="table-responsive" id="panel-oculto" style="display:none;" class"col-sm-2">
                    <div id="theTableDiccionario"></div>
                </div>
            </div>
            <a href="#" id="alternar-panel-oculto" onClick="showTableDic()">Consultar Variable</a><i class="glyphicon glyphicon-info-sign fa-1x" aria-hidden="true" style="color:blue"></i>
        </form>
        <form method="post" class="form-horizontal">
            <div class="panel">
                <div id="theTableAnimal"><b>Filtre el animal del cual desea consultar información</b></div>
            </div>
        </form>
    </div>
    <script src="https://code.jquery.com/jquery-1.11.1.min.js"></script> 
    <script src="https://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script>
        $( document ).ready(function() {
            $('#alternar-panel-oculto').toggle( 

                /* 
                    Primer click.
                    Función que descubre un panel oculto
                    y cambia el texto del botón.
                */
                function(e){ 
                    $('#panel-oculto').slideDown();
                    $(this).text('Consultar otra variable');
                    e.preventDefault();
                }, // Separamos las dos funciones con una coma

                /* 
                    Segundo click.
                    Función que oculta el panel
                    y vuelve a cambiar el texto del botón.
                */
                function(e){ 
                    $('#panel-oculto').slideUp();
                    $(this).text('Consultar Variable');
                    e.preventDefault();
                }
            );

            //este codigo reemplaza la funcion showTableAnimal y el "onClick="showTableAnimales();" que fue removido del boton "filtrar"
            $("#buttonFiltro").click(function(){

               var animal_id = $("#selAnimal").val();
               var localidad_id = <?php echo $_GET['id_Localidad']; ?>

               $.post('includes/getTablePorApoyar.php', { 
                    r: animal_id, 
                    id_localidad : localidad_id
                }, 
                function(returnedData){
                    console.log(returnedData);
                    $("#theTableAnimales").html(returnedData);
                }).fail(function(error){
                    console.log(error);
                });

            });
        });
    </script>
</body>
</html>
    
answered by 13.03.2018 / 19:44
source