Ajax Fill input fields from combobox

1

I need help because I can not achieve this: Here I have a code that I got on the web and adapted to fill dependent comboboxes. But I need that from the selection of the combo #sucursales the input field #Direccion is completed, obtaining data from a table of the DDBB. In the file "actioncombos.php" I included the query $ resultDirection in the function getInternos where I try to get the data I want to print in an input, but the result is null. I appreciate help. I leave my code:

solicitations.php

<div class="form-title">
    <div class="form-group">
        <label for="Cliente" id="BusClienteAbre"><a href="#">Cliente</a></label>
        <?php
        include("includes/conexion.php");
        $c=mysql_query("select id_cliente, razonsocial from clientes order by id_cliente ASC");
        ?>
        <select name="clientes" class="form-control" id="clientes">
            <option value="">-Seleccione Cliente-</option>
            <?php while($r= mysql_fetch_object($c)){
                echo "<option value=".$r->id_cliente.">".$r->id_cliente." - ".$r->razonsocial."</option>";
            } ?>
        </select>
    </div>
</div>              
<div class="row mb40">
    <div class="col-md-8">
        <div class="form-title">
            <div class="form-group"> 
                <label for="Sucursal">Sucursal</label> 
                <input type="text" name="NoSucursal" class="form-control" id="NoSucursal" size="7" maxlength="5" placeholder="C&oacute;d. Sucursal"> 
                <select name="sucursales" class="form-control" id="sucursales" disabled="disabled">
                    <option value="">-Sucursal-</option>
                </select>
            </div>
            <div class="form-group"> 
                <label for="Interno">Interno</label> 
                <input type="text" name="NoInterno" class="form-control" id="NoInterno" size="7" maxlength="5" placeholder="C&oacute;d. Interno"> 
                <select name="internos" class="form-control" id="internos" disabled="disabled">
                    <option value="">-Interno-</option>
                </select>
            </div>
            <div class="form-group"> 
                <label for="Direccion">Direccion</label> 
                <input type="text" name="Direccion" class="form-control" id="Direccion" size="20"> 
            </div>

procescombos.js

$(function() {
    $("#sucursales,#internos").attr('disabled', true);

    function ejecutar(obj1, obj2, task) {
        $('<img />', {
            'class': 'loading',
            src: 'images/ajax-loader.gif',
            'style': 'display:inline'
        }).insertAfter(obj1);

        $.ajax({
            type: "POST",
            url: "actioncombos.php",
            dataType: "html",
            data: "task=" + task + "&id=" + $(obj1).val(),
            success: function(msg) {
                $(obj1).next('img').remove();
                $(obj2).html(msg).attr("disabled", false);
            },
            error: function(jqXHR, textStatus, errorThrown) {
                $(obj1).next('img').remove();
                alert("Error al ejecutar => " + textStatus + " – " + errorThrown);
            }
        });
    }


    $("#clientes").change(function(e) {
        $("#internos,#sucursales,#Direccion").attr('disabled', true);
        if ($(this).val().trim() != "") {
            ejecutar($(this), $("#sucursales"), "getSucursales");
        }
    });
    $("#sucursales").change(function(e) {
        $("#internos").attr('disabled', true);
        if ($(this).val().trim() != "") {
            ejecutar($(this), $("#internos"), "getInternos");
        }
    });

});

actioncombos.php

<?php
include("includes/conexion.php");
function getSucursales() {
    $cliente = $_POST["id"];
    $resultSucursales = mysql_query("SELECT id_clienteSuc, id_sucursal, descripcion
     FROM sucursales 
     WHERE id_clienteSuc = '$cliente'
     ORDER BY id_sucursal ASC  
     "); 
    echo '<option value="0">-Seleccione sucursal-</option>'; 
    if ($rowSucursales = mysql_fetch_array($resultSucursales)){ 
        do { 
            echo '<option value="'.$rowSucursales["id_sucursal"].'">';
            echo ''.$rowSucursales["descripcion"].'</option>';
        }
        while ($rowSucursales = mysql_fetch_array($resultSucursales)); 
    } else { 
        echo '<option>Cliente sin Sucursales.</option>'; 
    }
}
function getInternos() {
    $sucursal = $_POST["id"];
    $resultInternos = mysql_query("SELECT id_intaut, id_cliente, id_sucursal, apellido, nombres
     FROM internosautorizados 
     WHERE id_sucursal = '$sucursal'
     ORDER BY id_intaut ASC  
     "); 
    echo '<option value="0">-Seleccione interno-</option>'; 
    if ($rowInterno = mysql_fetch_array($resultInternos)){ 
        do { 
            echo '<option value="'.$rowInterno["id_intaut"].'">';
            echo ''.$rowInterno["apellido"].', '.$rowInterno["nombres"].'</option>';
        }
        while ($rowInterno = mysql_fetch_array($resultInternos)); 
    } else { 
        echo '<option>Cliente sin Internos.</option>'; 
    }
    $resultDireccion = mysql_query("SELECT id_sucursal, id_clienteSuc, direccion, nro, piso, depto, localidad, provincia, telefono
     FROM sucursales 
     WHERE id_sucursal = '$sucursal'
     ORDER BY id_sucursal ASC  
     "); 
    while($row = mysql_fetch_array($resultDireccion)){
        echo '<input type="text" name="Direccion" class="form-control" id="Direccion" size="30" value="'.$row["direccion"].'" disabled> ';  
    }
}
if ($_POST) {
    switch ($_POST["task"]) {
        case "getSucursales":
        getSucursales();
        break;
        case "getInternos":
        getInternos();
        break;
    }
}
?>
    
asked by pointup 10.03.2017 в 16:19
source

2 answers

1

How are you using AJAX:

  • when #sucursales changes, get the val of the selection.

    $('#sucursales').on('change',function(){
      var direccion; //guardara la direccion obtenida
      var sucursal = $(this).val(); //obtiene la sucursal seleccioanada
    })
  • make the asynchronous AJAX request, pass the selected val and get results.

    $('#sucursales').on('change', function() {
      var direccion; //guardara la direccion obtenida
      var sucursal = $(this).val(); //obtiene la sucursal seleccioanada
    
      //petición ajax
      $.ajax({
        type: "POST",
        url: "actioncombos.php",
        dataType: "html",
        data: sucursal,
        async : false, //espera la respuesta antes de continuar
        success: function(respuesta) {
          direccion =  respuesta; //repuesta
        },
      });
    })
  • empty input #Direccion .

    $('#sucursales').on('change', function() {
      var direccion; //guardara la direccion obtenida
      var sucursal = $(this).val(); //obtiene la sucursal seleccioanada
    
      //petición ajax
      $.ajax({
        type: "POST",
        url: "actioncombos.php",
        dataType: "html",
        data: sucursal,
        async : false, //espera la respuesta antes de continuar
        success: function(respuesta) {
          direccion =  respuesta; //repuesta
        },
      });
    
      //limpia el input
      $('#direccion').val('');
    })
  • add new result to #Direccion .

    $('#sucursales').on('change', function() {
            var direccion; //guardara la direccion obtenida
      var sucursal = $(this).val(); //obtiene la sucursal seleccioanada
    
      //petición ajax
      $.ajax({
        type: "POST",
        url: "actioncombos.php",
        dataType: "html",
        data: sucursal,
        async : false, //espera la respuesta antes de continuar
        success: function(respuesta) {
          direccion =  respuesta; //repuesta
        },
      });
    
      //limpia el input
      $('#direccion').val('');
      //agrega la direccion
      $('#direccion').val(direccion);
    })
  • answered by 28.11.2017 в 17:14
    0

    what you could do is detect a change in your lists (combobox) with jQuery in the following way:

    $(documet).ready(function(){
        $("#id_de_tu_lista").on("change", function(){
            $("#id_de_tu_input").val(valor); //aqui le asignamos un valor el cual usted define
        });
    });
    

    with this it detects when an option is chosen in it gives a value to the input.

        
    answered by 14.03.2017 в 04:09