problem with ajax and php: error php undefined index country

2

I describe my problem: the objective is to integrate the use of ajax with php code. I have a php called country in which there is a drop-down form and will follow the following instructions when selecting a value will call the function ajax, the ajax function will call another php:

The other php will read from the country database of the provinces table that contains the provinces of the selected country and a drop-down will be shown with these provinces.

My error is as follows: Notice: undefined index pais in leerbd.php on line 26 ($ query="SELECT * FROM provincias where pais = '". $ _ GET [' pais ']. "'";) '

pais.php:

<?php




include 'leerbd.php';


?>

<html>
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>
    <section>

    <form action="" method="post" align="center">
            Pais: <select name="pais" id="pais" onchange="Provincias()"> <!-- en el onchange le ponemos el nombre de la funcion-->
            <option value="">[Seleccione el pais]</option> 
            <option value="es">España</option>
            <option value="pt">Portugal</option>
        </select><br />
        <div id="provincias"></div>  
    </form>





    </section>

    <script type="text/javascript">
    /*función para crear el objeto de AJAX que permite la conexión*/

        function getHTTPObject(){
            if (window.ActiveXObject)
                return new ActiveXObject("Microsoft.XMLHTTP");
            else if (window.XMLHttpRequest)
                return new XMLHttpRequest();
            else {
                alert("No soportado"); 
                return null;
            }

        }



        function Provincias(){
            var pais = document.getElementById('pais').value; //recogemos el pais
            httpObject = getHTTPObject(); 
            if (httpObject != null) {
                httpObject.open("GET", "leerbd.php?pais=" + pais ,true); 
                httpObject.onreadystatechange = function()
                {
                    if(httpObject.readyState == 4  && httpObject.status == 200) 
                    /*cuando acabe de cargar leerbd.php /*mostramos el contenido generado en suma.php */
                    {

                         document.getElementById('provincias').innerHTML = httpObject.responseText;
                    }
                }
                httpObject.send(null);
            }
        } 



    </script>



</body>
</html>

leerbd.php:

<?php

//Conectando y seleccionando la base de datos

$conexion = mysqli_connect('localhost', 'root', '') or die('No pudo conectarse: ' .mysqli_error());


echo 'Conexion correcta </br>';



mysqli_select_db($conexion, 'paises') or die('No se pudo seleccionar la base de datos');
    echo 'Provincia : <select id="provincia" name="provincia">';

    $query = "SELECT * FROM provincias where pais =  '".$_GET['pais']."'";

    //echo $query;
    $result = mysqli_query($conexion, $query) or die('Consulta fallida: ' .mysqli_error());
    if($result){
        echo 'llego </br>';
        //si tenemos registros
        $row_cnt = mysqli_num_rows($result);
        if($row_cnt !== 0) {
            echo 'llego 2';
            while($row = mysqli_fetch_array($result)) {
                echo '<option value="'.$row['id'].'">'.$row['provincia'].'</option>';
            }   
        } else {
            echo 'No se han encontrado registros';
        }
    }


    echo '</select>';
    mysqli_close($conexion);


?>

'

    
asked by Dani Serra 29.05.2018 в 10:15
source

2 answers

0

Your problem is this:

<?php




include 'leerbd.php';


?>

Since that is going to load the php file on your page when loading this. To make the ajax request you do not need to import the file, you just have to specify which route you want to call, by doing include , within leerbd.php you are waiting for a $_GET['pais'] parameter, which at the beginning it does not exist, that will always petar you. I hope it has served you:)

    
answered by 29.05.2018 в 11:07
0

Dani, the main problem with your code is that you are sending nothing when doing this:

httpObject.send(null); 1

Try this way:

function Provincias(){
        var pais = document.getElementById('pais').value; //recogemos el pais
        httpObject = getHTTPObject(); 
        if (httpObject != null) {
            httpObject.open("POST", "leerbd.php", true); 
            httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            httpObject.send("pais="+pais);

            httpObject.onreadystatechange = function()
            {
                if(httpObject.readyState == 4  && httpObject.status == 200) 
                /*cuando acabe de cargar leerbd.php /*mostramos el contenido generado en suma.php */
                {

                     document.getElementById('provincias').innerHTML = httpObject.responseText;
                }
            }
        }
    }
  

NOTE ON SECURITY

     

The code in leerbd.php is vulnerable to SQL injection attacks. Yes   you are interested in correcting that error, once the problem has been solved   original proposal, you mention it to suggest a code correcting   that failure.

1 Interestingly, the MDN documentation in Spanish shows erroneous examples about the send method, indicating that this method can be sent null , which would not make any sense. The code between the English version (correct) and version in Spanish (incorrect), is completely different in terms of the use of send .

    
answered by 29.05.2018 в 12:02