Problem with jquery Notice: Undefined index

0

Good morning I have a problem with the combobox and the jquery , the event is not "activated" from the drop-down menu (I have 2 dependent menus mark-> model)

script that is in the html head

    <script language="javascript" src="js/jquery-3.2.1.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
        $("cbx_marca").change(function () {
            id_marca = $(this).val()
            $.ajax({
              type:"POST",
              url:"includes/getMarca.php", 
              data:{ id_marca: id_marca },
              success: function(data){
             $("cbx_modelo").html(data);
               }
             })
        })
    });
</script>

HTML

       <form id="combo" name="combo" method="POST" action="guardar.php">

        <div>Seleccione la Marca: 
            <select id="cbx_marca" name="cbx_marca">
                <option value="0">Seleccionar Marca</option>

                <?php WHILE ($row=$resultado->fetch_assoc()){ ?>

                <option value="<?php echo $row["IdMarca"];?>"><?php echo 
               $row["NombreMarca"];?></option>

                <?php } ?>

            </select>
        </div>
        <div>Seleccione el Modelo: 
            <select id="cbx_modelo" name="cbx_modelo">
            </select>
        </div>
        <input type="submit" id="enviar" name="enviar" value="Guardar" />
    </form>

The getMarca file

   require ('../conexion.php');

  if ( !empty($_POST['id_marca'])) {
      $id_marca = (int)$_POST['id_marca'];
       }
        else{
         echo 'NO se recibieron datos POST';
           $id_marca = 2;
         }
       $query2 = "SELECT IdModelo, NombreModelo FROM modelo WHERE IdMarca = 
         '$id_marca' ORDER BY NombreModelo";
       $resultado2 = $mysqli->query($query2);

         $html= "<option value='0'>Seleccionar Modelo</option>";

while($row2 = $resultado2->fetch_assoc())
{
    $html.= "<option value='".$row2['IdModelo']."'>".$row2['NombreModelo']."</option>";
}

echo $html;

With the if of getMarca, I checked that the post does not arrive and I would not know if it is because the events are not "activated" or I'm doing something wrong.

Excuse my ignorance I am still studying and I hope you can help me.

  

PS: It's the first time I use this page, if I'm missing something or anything, tell me.

     

Last edition and functional

 <script language="javascript">
$(document).ready(function(){
    $("#cbx_marca").change(function () {

        $("#cbx_marca option:selected").each(function () {
            id_marca = $(this).val();
            $.ajax({
                 type:"POST",
                 url:"includes/getMarca.php", 
                 data:{ id_marca: id_marca },
                 success: function(data){
                             $("#cbx_modelo").html(data);
                           }
                })            
        });
    })
});

    
asked by Enrique Menendez 21.12.2017 в 21:18
source

3 answers

1

Make the request of script of head like this:

<script language="javascript">
    $(document).ready(function(){
        $("#cbx_marca").change(function () {

            $("#cbx_marca option:selected").each(function () {
                id_marca = $(this).val();
                $.ajax({
                     type:"POST",
                     url:"includes/getMarca.php", 
                     data:{ id_marca: id_marca },
                     success: function(data){
                                 $("#cbx_modelo").html(data);
                               }
                    })            
            });
        })
    });
</script>
    
answered by 21.12.2017 / 21:24
source
0

I will propose this (partial) solution, since certain inconsistencies persist in your code. For example, if there is no id_brand in the request, you set its value to 2 and at the same time you do a echo saying that a id_brand was not posted.

The Ajax request did not handle a fail method that warns you if there is an error, for example, in the file's url.

SQL queries are vulnerable. Once solved the main problem I will propose a safe solution in that sense.

You can optimize the handling of the query and its results, for example, if it throws zero rows, etc.

Also, I'm implementing updated jQuery code, using function , as well as done instead of success .

I made other improvements to the code. Test and comment on the results.

jQuery

$(function() {

    $('#cbx_marca').on('change', function() {
        var id_marca = $(this).val();
        var data= { id_marca: id_marca };
        var request = $.ajax({
            url: 'includes/getMarca.php',
            method: 'POST',
            data: data,
            dataType: 'html'
        });

        request.done(function(respuesta) {
            console.log(respuesta);
            $("#cbx_modelo").html(respuesta);                           

        });
        request.fail(function(jqXHR, textStatus) {
            alert("Hubo un error: " + textStatus);
        });


    })
});

getMarca.php

require ('../conexion.php');

if (isset($_POST['id_marca'])) 
{
    $id_marca = (int)$_POST['id_marca'];
}else{
    //echo 'NO se recibieron datos POST'; //???
    $id_marca = 2; //????
}
$query2 = "SELECT IdModelo, NombreModelo FROM modelo WHERE IdMarca = ? ORDER BY NombreModelo";
$resultado2 = $mysqli->query($query2);

$html= '<option value="0">Seleccionar Modelo</option>';

while($row2 = $resultado2->fetch_assoc())
{
    $html.= '<option value='"'.$row2["IdModelo"].'"'>'.$row2["NombreModelo"].'</option>';
}

echo $html;
    
answered by 21.12.2017 в 22:16
0

A little late, but I just saw the problem with your original code . You had this:

$.post("includes/getMarca.php", { id_marca: id_marca }, function(data){ 
   $("#cbx_modelo").html(data); 
});

But what is "includes/getMarca.php" ? Or { id_marca: id_marca } ? Or the function of the end? You needed to set the parameters of $.post correctly (with a name and between braces {} .

The correct thing would have been as specified in the jQuery documentation :

$.post({
   url: "includes/getMarca.php", 
   data: { id_marca: id_marca }, 
   success: function(data){ 
       $("#cbx_modelo").html(data); 
   }
});

Travv's solution works because it puts the names of the parameters well in $.ajax . If you had put them the same, it would have worked for you because%% of% is equivalent to%% co with POST.

    
answered by 21.12.2017 в 22:31