Foros del Web » Programando para Internet » Jquery »

Problema con select dependientes y ajax

Estas en el tema de Problema con select dependientes y ajax en el foro de Jquery en Foros del Web. Buenas Tardes Llevo días peleándome con unos select dependientes, que el primero me desaparece cuando selecciono la option que quiero, aunque si mostrándome el contenido ...
  #1 (permalink)  
Antiguo 11/08/2015, 09:03
 
Fecha de Ingreso: agosto-2015
Mensajes: 4
Antigüedad: 8 años, 8 meses
Puntos: 0
Problema con select dependientes y ajax

Buenas Tardes

Llevo días peleándome con unos select dependientes, que el primero me desaparece cuando selecciono la option que quiero, aunque si mostrándome el contenido que tiene que ser en el segundo select. Os adjunto unas capturas del proceso.





Os pongo el codigo de los 3 ficheros tal cual lo tengo, a ver si a alguien se le ocurre como evitar que desaparezca el primer combo

cerrar.php
Código PHP:
Ver original
  1. <? require "setup.php"; $seccion = "";
  2. if(!$_GET[centro]) { $url="blanco"; } else { $url="$_GET[centro]"; }
  3. $numerorden = $_GET['orden'];
  4. $comerci = $_GET['comercio'];
  5. $materi = $_GET['material'];
  6. $typi = $_GET['type'];
  7. $tipocierre = $_GET['d'];
  8. $fecha = date ('Y-m-d  H:i:00');
  9. $camb = $_GET['typu'];
  10.  
  11.  
  12.  
  13. function generaestados($rt, $tt)
  14. {
  15.     include_once 'conexion.php';
  16.     conectar();
  17.     $consulta=mysql_query("SELECT * FROM estados where estado = '$rt' and usarpara = '$tt'");
  18.     desconectar();
  19.     // Voy imprimiendo el primer select compuesto por los paises
  20.     echo "<select name='estado' id='estado' onChange='mostrar(this.value)';>";
  21.     echo "<option value='0'></option>";
  22.     while($registro=mysql_fetch_row($consulta))
  23.     {
  24.         echo "<option value='".$registro[3]."'>".$registro[4]."</option>";
  25.     }
  26.     echo "</select>";
  27.    
  28. }
  29. function generaequipos($gh, $pl, $ty)
  30. {
  31.  
  32.     include_once 'conexion.php';
  33.     conectar();
  34.     $consulta3=mysql_query("SELECT DISTINCT cod_equipo FROM equipos where cod_equipo LIKE '$gh%' and ubicacion = '$pl' and tipo='$ty' and averiado ='NO'");
  35.     desconectar();
  36.     // Voy imprimiendo el primer select compuesto por los paises
  37.     echo "<select name='equipo' id='equipo' onChange='cargaContenido(this.id)'>";
  38.     echo "<option value='0'>Elige</option>";
  39.     while($registro3=mysql_fetch_row($consulta3))
  40.     {
  41.         echo "<option value='".$registro3[0]."'>".$registro3[0]."</option>";
  42.     }
  43.     echo "</select>";
  44.    
  45. }
  46. function generaequiporetir($gh)
  47. {
  48.     include_once 'conexion.php';
  49.     conectar();
  50.     $consulta2=mysql_query("SELECT * FROM productos where codequipo LIKE '$gh%'");
  51.     desconectar();
  52.     // Voy imprimiendo el primer select compuesto por los paises
  53.     echo "<select name='equipo' id='equipo';>";
  54.     echo "<option value='0'></option>";
  55.     while($registro2=mysql_fetch_row($consulta2))
  56.     {
  57.         echo "<option value='".$registro2[1]."'>".$registro2[1]."</option>";
  58.     }
  59.     echo "</select>";
  60. }
  61. function rellenaretirado($te)
  62. {
  63.     include_once 'conexion.php';
  64.     conectar();
  65.     $we=mysql_query("SELECT * FROM comercios where numcomercio = '$te'");
  66.     while ($ro = mysql_fetch_array($we)) {
  67. $modequip = ($ro[modeloequipo]);
  68. $seryal = ($ro[serial]);
  69.     }
  70.     desconectar();
  71.     // Voy imprimiendo el primer select compuesto por los paises
  72.     echo "
  73.     <input type=\"text\" name=\"modequipo\" id=\"modequipo\" readonly=\”readonly\”  value=\"$modequip\">
  74.     <input type=\"text\" name=\"seryal\" id=\"seryal\" readonly=\”readonly\”  value=\"$seryal\">
  75.     ";
  76. }
  77. ?>
  78.  
  79. <html>
  80. <script type="text/javascript" src="select_dependientes.js"></script>
  81. <head>
  82. <title></title>
  83. <link rel="stylesheet" href="estilos.css" type="text/css">
  84.  
  85.  
  86. </head>
  87. <body topmargin="0" leftmargin="0" bgcolor="#666666" text="#000000" link="#FFFF40" alink="#FFFF40" vlink="#FFFF40">
  88.  
  89. <table border="0" width="968" align="center" cellspacing="1" bgcolor="#606060" cellpadding="1">
  90. <tr bgcolor="#606060">
  91. <td colspan="3" align="center">
  92. <img src="pto.jpg" height="1" width="1" border="0">
  93. </td>
  94. </tr>
  95. <tr bgcolor="#070707">
  96. <td colspan="3" align="left" height="120" valign="middle">
  97. <img src="logo.jpg" width="968" height="121" border="0">
  98. </td>
  99. </tr>
  100. <tr bgcolor="#313b83">
  101. <td colspan="3" align="right" height="30">
  102. <? include "secciones.php"; ?>
  103. </td>
  104. </tr>
  105. <tr bgcolor="#c6c5c5">
  106. <td width="800" valign="top">
  107. <br><br><br><br>
  108.  
  109. <?
  110.  
  111. if ($tipocierre=='ok' or $tipocierre=='Cerrar OK' ) {
  112. echo"
  113.  
  114. <form action=\"cerrar2.php\" method=\"get\" name=\"d\">
  115. <center><table class=\"tg\">
  116.  <tr>
  117.    <th class=\"tg-031e\">Orden de Trabajo:</th>
  118.    <th class=\"tg-031e\"><input type=\"text\" name=\"ordenot\" readonly=\”readonly\”  size=\"15\" value=\"$numerorden\"></th>
  119.  </tr>
  120.  <tr>
  121.    <td class=\"tg-031e\">Estado Cierre:</td>
  122.    <td class=\"tg-031e\">"; generaestados(OK, $camb); echo"</td>
  123.  </tr>
  124.  <tr>
  125.    <td class=\"tg-031e\">Fecha Cierre:</td>
  126.    <td class=\"tg-031e\"><input type=\"text\" name=\"fechacierres\" id=\"fechacierres\" value=\"$fecha\"></td>
  127.  </tr></table>
  128.  <div id=\"0\" style=\"display: none;\"></div>
  129.  
  130.  <div id=\"COMPOK\" style=\"display: none;\">
  131.  <table class=\"tg\"><tr>
  132.    <td class=\"tg-031e\">EQUIPO INSTALADO:</td>
  133.    <td class=\"tg-031e\">"; generaequipos($materi, $user_id, $typi); echo" <select disabled=\"disabled\" name=\"numserie\" id=\"numserie\"><option value=\"0\">Selecciona numero de serie...</option></select></td>
  134.     </tr>
  135.     <tr>
  136.    <td class=\"tg-031e\">Comentario:</td>
  137.    <td class=\"tg-031e\"><textarea name=\"comentarios\" rows=\"10\" cols=\"40\"></textarea></td>
  138.  </tr>
  139.  </table>
  140.  <input type=\"submit\" value=\"CERRAR\" name=\"d\"/>
  141.  </form>
  142.  </div>
  143.  
  144. <div id=\"COMPCAMB\" style=\"display: none;\">
  145.  <table class=\"tg\"><tr>
  146.    <td class=\"tg-031e\">EQUIPO INSTALADO:</td>
  147.    <td class=\"tg-031e\">"; generaequipos($materi, $user_id, $typi); echo" <select disabled=\"disabled\" name=\"numserie\" id=\"numserie\"><option value=\"0\">Selecciona numero de serie...</option></select></td>
  148.     </tr>
  149.     <tr>
  150.    <td class=\"tg-031e\">EQUIPO RETIRADO:</td>
  151.    <td class=\"tg-031e\">"; rellenaretirado($comerci); echo"</td>
  152.     </tr>
  153.     <tr>
  154.    <td class=\"tg-031e\">Comentario:</td>
  155.    <td class=\"tg-031e\"><textarea name=\"comentarios\" rows=\"10\" cols=\"40\"></textarea></td>
  156.  </tr>
  157.  </table>
  158.  <input type=\"submit\" value=\"CERRAR\" name=\"d\"/>
  159. </form>
  160.  </div>
  161.  
  162.  <div id=\"COMPOKRET\" style=\"display: none;\">
  163.  <table class=\"tg\">
  164.     <tr>
  165.    <td class=\"tg-031e\">EQUIPO RETIRADO:</td>
  166.    <td class=\"tg-031e\">"; rellenaretirado($comerci); echo"</td>
  167.     </tr>
  168.     <tr>
  169.    <td class=\"tg-031e\">Comentario:</td>
  170.    <td class=\"tg-031e\"><textarea name=\"comentarios\" rows=\"10\" cols=\"40\"></textarea></td>
  171.  </tr>
  172.  </table>
  173.  <input type=\"submit\" value=\"CERRAR\" name=\"d\"/>
  174. </form>
  175.  </div>
  176.  
  177. <div id=\"COMPOKREQ\" style=\"display: none;\">
  178. <table>
  179. <tr>
  180.    <td class=\"tg-031e\">Comentario:</td>
  181.    <td class=\"tg-031e\"><textarea name=\"comentarios\" rows=\"10\" cols=\"40\"></textarea></td>
  182.  </tr>
  183.  </table>
  184.  <input type=\"submit\" value=\"CERRAR\" name=\"d\"/>
  185. </form>
  186. </div>
  187. </center>
  188.  
  189.  
  190.  
  191.      
  192.      
  193. ";
  194.  
  195.  
  196. }
  197.  
  198.  
  199. else{
  200.  
  201. echo "
  202. <form action=\"cerrar2.php\" method=\"get\" name=\"d\">
  203. <center><table class=\"tg\">
  204.  <tr>
  205.    <th class=\"tg-031e\">Orden de Trabajo:</th>
  206.    <th class=\"tg-031e\"><input type=\"text\" name=\"ordenot\" readonly=\”readonly\”  size=\"15\" value=\"$numerorden\"></th>
  207.  </tr>
  208.  <tr>
  209.    <td class=\"tg-031e\">Estado Cierre:</td>
  210.    <td class=\"tg-031e\">"; generaestados(FA); echo"</td>
  211.  </tr>
  212.  <tr>
  213.    <td class=\"tg-031e\">Fecha Cierre:</td>
  214.    <td class=\"tg-031e\"><input type=\"text\" name=\"fechacierres\" id=\"fechacierres\" value=\"$fecha\"></td>
  215.  </tr>
  216.  </table>
  217.  <div id=\"0\" style=\"display: none;\"></div>
  218.  <div id=\"FALLIDA\" style=\"display: none;\">
  219. <table class=\"tg\">
  220.  <tr>
  221.    <td class=\"tg-031e\">Comentario:</td>
  222.    <td class=\"tg-031e\"><textarea name=\"comentarios\" rows=\"10\" cols=\"40\"></textarea></td>
  223.  </tr>
  224. </table>
  225. <input type=\"submit\" value=\"CERRAR\" name=\"d\"/>
  226. </center></form>
  227. </div>";
  228.  }
  229. ?>
  230. <br><br><br>
  231. </center>
  232. </td>
  233. </tr>
  234. <tr bgcolor="#313b83"><td colspan="3" align="center" height="70" valign="bottom">
  235. </td></tr>
  236. <tr bgcolor="#606060"><td colspan="3" align="center" class="v10"><? include "abajo.php"; ?></td></tr>
  237. </table>
  238. </body>
  239. </html>
  #2 (permalink)  
Antiguo 11/08/2015, 09:04
 
Fecha de Ingreso: agosto-2015
Mensajes: 4
Antigüedad: 8 años, 8 meses
Puntos: 0
Respuesta: Problema con select dependientes y ajax

Aquí el resto

select_dependientes.js

Código PHP:
Ver original
  1. function nuevoAjax()
  2. {
  3.     /* Crea el objeto AJAX. Esta funcion es generica para cualquier utilidad de este tipo, por
  4.     lo que se puede copiar tal como esta aqui */
  5.     var xmlhttp=false;
  6.     try
  7.     {
  8.         // Creacion del objeto AJAX para navegadores no IE
  9.         xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
  10.     }
  11.     catch(e)
  12.     {
  13.         try
  14.         {
  15.             // Creacion del objet AJAX para IE
  16.             xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  17.         }
  18.         catch(E)
  19.         {
  20.             if (!xmlhttp && typeof XMLHttpRequest!='undefined') xmlhttp=new XMLHttpRequest();
  21.         }
  22.     }
  23.     return xmlhttp;
  24. }
  25.  
  26. // Declaro los selects que componen el documento HTML. Su atributo ID debe figurar aqui.
  27. var listadoSelects=new Array();
  28. listadoSelects[0]="equipo";
  29. listadoSelects[1]="numserie";
  30.  
  31. function buscarEnArray(array, dato)
  32. {
  33.     // Retorna el indice de la posicion donde se encuentra el elemento en el array o null si no se encuentra
  34.     var x=0;
  35.     while(array[x])
  36.     {
  37.         if(array[x]==dato) return x;
  38.         x++;
  39.     }
  40.     return null;
  41. }
  42.  
  43. function cargaContenido(idSelectOrigen)
  44. {
  45.     // Obtengo la posicion que ocupa el select que debe ser cargado en el array declarado mas arriba
  46.     var posicionSelectDestino=buscarEnArray(listadoSelects, idSelectOrigen)+1;
  47.     // Obtengo el select que el usuario modifico
  48.     var selectOrigen=document.getElementById(idSelectOrigen);
  49.     // Obtengo la opcion que el usuario selecciono
  50.     var opcionSeleccionada=selectOrigen.options[selectOrigen.selectedIndex].value;
  51.     // Si el usuario eligio la opcion "Elige", no voy al servidor y pongo los selects siguientes en estado "Selecciona opcion..."
  52.     if(opcionSeleccionada==0)
  53.     {
  54.         var x=posicionSelectDestino, selectActual=null;
  55.         // Busco todos los selects siguientes al que inicio el evento onChange y les cambio el estado y deshabilito
  56.         while(listadoSelects[x])
  57.         {
  58.             selectActual=document.getElementById(listadoSelects[x]);
  59.             selectActual.length=0;
  60.            
  61.             var nuevaOpcion=document.createElement("option"); nuevaOpcion.value=0; nuevaOpcion.innerHTML="Selecciona Opci&oacute;n...";
  62.             selectActual.appendChild(nuevaOpcion);  selectActual.disabled=true;
  63.             x++;
  64.         }
  65.     }
  66.     // Compruebo que el select modificado no sea el ultimo de la cadena
  67.     else if(idSelectOrigen!=listadoSelects[listadoSelects.length-1])
  68.     {
  69.         // Obtengo el elemento del select que debo cargar
  70.         var idSelectDestino=listadoSelects[posicionSelectDestino];
  71.         var selectDestino=document.getElementById(idSelectDestino);
  72.         // Creo el nuevo objeto AJAX y envio al servidor el ID del select a cargar y la opcion seleccionada del select origen
  73.         var ajax=nuevoAjax();
  74.         ajax.open("GET", "select_dependientes_proceso.php?select="+idSelectDestino+"&opcion="+opcionSeleccionada, true);
  75.         ajax.onreadystatechange=function()
  76.         {
  77.             if (ajax.readyState==1)
  78.             {
  79.                 // Mientras carga elimino la opcion "Selecciona Opcion..." y pongo una que dice "Cargando..."
  80.                 selectDestino.length=0;
  81.                 var nuevaOpcion=document.createElement("option"); nuevaOpcion.value=0; nuevaOpcion.innerHTML="Cargando...";
  82.                 selectDestino.appendChild(nuevaOpcion); selectDestino.disabled=true;   
  83.             }
  84.             if (ajax.readyState==4)
  85.             {
  86.                 selectDestino.parentNode.innerHTML=ajax.responseText;
  87.             }
  88.         }
  89.         ajax.send(null);
  90.     }
  91. }

select_dependientes_proceso.php

Código PHP:
Ver original
  1. <?php
  2. // Array que vincula los IDs de los selects declarados en el HTML con el nombre de la tabla donde se encuentra su contenido
  3. $listadoSelects=array(
  4. "paises"=>"equipos",
  5. "numserie"=>"equipos",
  6. );
  7.  
  8. function validaSelect($selectDestino)
  9. {
  10.     // Se valida que el select enviado via GET exista
  11.     global $listadoSelects;
  12.     if(isset($listadoSelects[$selectDestino])) return true;
  13.     else return false;
  14. }
  15.  
  16. function validaOpcion($opcionSeleccionada)
  17. {
  18.     // Se valida que la opcion seleccionada por el usuario en el select tenga un valor numerico
  19.     if(is_numeric($opcionSeleccionada)) return false;
  20.     else return true;
  21. }
  22.  
  23. $selectDestino=$_GET["select"]; $opcionSeleccionada=$_GET["opcion"];
  24.  
  25. if(validaSelect($selectDestino) && validaOpcion($opcionSeleccionada))
  26. {
  27.    
  28.     $tabla=$listadoSelects[$selectDestino];
  29.     include 'conexion.php';
  30.     conectar();
  31.     $consulta=mysql_query("SELECT * FROM $tabla WHERE cod_equipo='$opcionSeleccionada'") or die(mysql_error());
  32.     desconectar();
  33.    
  34.     // Comienzo a imprimir el select
  35.     echo "<select name='".$selectDestino."' id='".$selectDestino."' onChange='cargaContenido(this.id)'>";
  36.  
  37.     while($registro=mysql_fetch_row($consulta))
  38.     {
  39.         // Convierto los caracteres conflictivos a sus entidades HTML correspondientes para su correcta visualizacion
  40.         $registro[1]=htmlentities($registro[1]);
  41.         // Imprimo las opciones del select
  42.         echo "<option value='".$registro[3]."'>".$registro[3]."</option>";
  43.     }          
  44.     echo "</select>";
  45. }
  46. ?>
  #3 (permalink)  
Antiguo 11/08/2015, 09:41
 
Fecha de Ingreso: agosto-2015
Mensajes: 4
Antigüedad: 8 años, 8 meses
Puntos: 0
Respuesta: Problema con select dependientes y ajax

Me falto añadir en cerrar.php el siguiente código para que muestre u oculte los div

Código PHP:
Ver original
  1. <script type="text/javascript">
  2. function mostrar(id) {
  3.     if (id == "0") {
  4.         $("#0").hide();
  5.         $("#COMPOK").hide();
  6.         $("#COMPCAMB").hide();
  7.         $("#COMPOKREQ").hide();
  8.         $("#FALLIDA").hide();
  9.         $("#COMPOKRET").hide();
  10.        
  11.     }
  12.     if (id == "COMPOK") {
  13.         $("#0").hide();
  14.         $("#COMPOK").show();
  15.         $("#COMPCAMB").hide();
  16.         $("#COMPOKREQ").hide();
  17.         $("#COMPOKRET").hide();
  18.     }
  19.  
  20.     if (id == "COMPCAMB") {
  21.         $("#0").hide();
  22.         $("#COMPOK").hide();
  23.         $("#COMPCAMB").show();
  24.         $("#COMPOKREQ").hide();
  25.         $("#COMPOKRET").hide();
  26.     }
  27.  
  28.     if (id == "COMPOKREQ") {
  29.         $("#0").hide();
  30.         $("#COMPOK").hide();
  31.         $("#COMPCAMB").hide();
  32.         $("#COMPOKREQ").show();
  33.         $("#COMPOKRET").hide();
  34.        
  35.     }
  36.     if (id == "COMPOKRET") {
  37.         $("#0").hide();
  38.         $("#COMPOK").hide();
  39.         $("#COMPCAMB").hide();
  40.         $("#COMPOKREQ").hide();
  41.         $("#COMPOKRET").show();
  42.        
  43.     }
  44.     if (id == "COMPFALCO") {
  45.         $("#0").hide();
  46.         $("#FALLIDA").show();
  47.                
  48.     }
  49.     if (id == "COMPFAVAS") {
  50.         $("#0").hide();
  51.         $("#FALLIDA").show();
  52.        
  53.     }
  54.  
  55.    
  56. }
  57. </script>

Etiquetas: ajax, dependientes, select
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 09:22.