简体   繁体   中英

jQuery AJAX post not working with my php code

I'm trying to do a dynamic select. You are supposed to first select the state (id = "edo") and then select the city (id = "municipio"). Both selects retrieve the information from my database; however when I try to get the city select to respond dynamically through post with AJAX, nothing changes. I run directly my page getMunicipio.php and what I get is Notice: Undefined index: id_estado in C:\\xampp\\htdocs\\nthlife\\js\\getMunicipio.php on line 9

Can you help me? Here is my JavaScript code.

$(document).ready(function (){
  $("#edo").change(function () {
    $("#edo option:selected").each(function () {
      id_estado = $(this).val();
      //alert(id_estado);
      $.post("getMunicipio.php", { id_estado: id_estado }, function(data){
        $("#municipio").html(data);
      });            
    });
  })
});

And this is the code in getMunicipio.php

include "../includes/conexionbd.php";

//var_dump($_POST);

//if (isset($_POST['id_estado']))
{
    $id_estado = $_POST['id_estado'];

    $queryM = "SELECT * FROM municipios WHERE estado = '".$id_estado."'";
    $resultadoM = mysqli_query($conexion, $queryM) or die(mysqli_error($conexion));

    $check = mysqli_num_rows($resultadoM);
    $html= "<option value='0'>" . $check . "</option>";

    while($rowM = mysqli_fetch_array($resultadoM))
    {
        $html.= "<option value='".$rowM['id_municipio']."'>".$rowM['nombre_municipio']."</option>";
    }

    echo $html;
}

Thank you.

Really need to see your HTML, but from what you have posted the javascript side should work.

What do you see in var_dump($_POST) ? Running the page directly is probably throwing an error because your POST variable is not set and your if (isset($_POST['id_estado'])) condition is commented out. You should change the condition to if (!empty($_POST['id_estado'])) as if the form posts this with an empty value it will still be set, but it will be empty.

You are using double quotes to create your strings, so escaping the variables is unnecessary as PHP will parse them.

These:

$html= "<option value='0'>" . $check . "</option>";
$queryM = "SELECT * FROM municipios WHERE estado = '".$id_estado."'";

Can become these:

$html= "<option value='0'>$check</option>";
$queryM = "SELECT * FROM municipios WHERE estado = '$id_estado'";

However, you can't use single quoted array keys in a double quoted string.

Change this:

$html.= "<option value='".$rowM['id_municipio']."'>".$rowM['nombre_municipio']."</option>";

To this:

$html.= "<option value='{$rowM['id_municipio']}'>{$rowM['nombre_municipio']}</option>";

Or this:

$html.= "<option value='$rowM[id_municipio]'>$rowM[nombre_municipio]</option>";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM