Foros del Web » Programando para Internet » Jquery »

Tres select dependientes que no funcionan

Estas en el tema de Tres select dependientes que no funcionan en el foro de Jquery en Foros del Web. No me carga los select de estado y ciudad Gracias Código PHP: <?php  require_once( '../Connections/conexion.php' );  ?> <?php  include( '../lang/lang.php' );  ?> <?php  include( '../inc/config.php' ...
  #1 (permalink)  
Antiguo 31/03/2016, 09:16
 
Fecha de Ingreso: marzo-2016
Mensajes: 6
Antigüedad: 8 años, 1 mes
Puntos: 0
Tres select dependientes que no funcionan

No me carga los select de estado y ciudad
Gracias
Código PHP:
<?php require_once('../Connections/conexion.php'); ?>
<?php 
include('../lang/lang.php'); ?>
<?php 
include('../inc/config.php'); ?>
<?php 
if (!function_exists("GetSQLValueString")) {
function 
GetSQLValueString($theValue$theType$theDefinedValue ""$theNotDefinedValue ""
{
  if (
PHP_VERSION 6) { $theValue get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; }
  
$theValue function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
  switch (
$theType) {
    case 
"text":
      
$theValue = ($theValue != "") ? "'" $theValue "'" "NULL";
      break;    
    case 
"long":
    case 
"int":
      
$theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case 
"double":
      
$theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case 
"date":
      
$theValue = ($theValue != "") ? "'" $theValue "'" "NULL";
      break;
    case 
"defined":
      
$theValue = ($theValue != "") ? $theDefinedValue $theNotDefinedValue;
      break; }
  return 
$theValue; } } 
mysql_select_db($database_conexion$conexion);
$query_pais "SELECT * FROM countries ORDER BY name ASC";
$pais mysql_query($query_pais$conexion) or die(mysql_error());
$row_pais mysql_fetch_assoc($pais);
$totalRows_pais mysql_num_rows($pais);
$colname_estado "-1";
if (isset(
$_POST['id'])) {

  
$colname_estado $_POST['id']; }
mysql_select_db($database_conexion$conexion);
$query_estado sprintf("SELECT * FROM states WHERE country_id = %s ORDER BY name ASC"GetSQLValueString($colname_estado"int"));
$estado mysql_query($query_estado$conexion) or die(mysql_error());
$row_estado mysql_fetch_assoc($estado);
$totalRows_estado mysql_num_rows($estado);
$colname_ciudad "-1";
if (isset(
$_POST['id'])) {

  
$colname_ciudad $_POST['id']; }
mysql_select_db($database_conexion$conexion);
$query_ciudad sprintf("SELECT * FROM cities WHERE state_id = %s ORDER BY name ASC"GetSQLValueString($colname_ciudad"int"));
$ciudad mysql_query($query_ciudad$conexion) or die(mysql_error());
$row_ciudad mysql_fetch_assoc($ciudad);
$totalRows_ciudad mysql_num_rows($ciudad); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
<head>
<meta http-equiv="Content-Type" content="text/html; />
<title></title>
<script type="text/javascript" src="../js/combo_dependientes.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<select name="country" class="countries" id="countryId">
<option value="">Select Country</option>
<option value="0" selected="selected"><?php echo $TEXT['acceso-co_error']; ?></option>
                            <?php do { ?>
                            <option value="<?php echo $row_pais['id']?>"><?php echo $row_pais['name']?></option>
                            <?php } while ($row_pais mysql_fetch_assoc($pais));
                                    
$rows mysql_num_rows($pais);
                                    if(
$rows 0) {
                                       
mysql_data_seek($pais0);
                                       
$row_pais mysql_fetch_assoc($pais); } ?>
</select>
<select name="state" class="states" id="stateId">
<option value="">Select State</option>
<option value="0" selected="selected"><?php echo $TEXT['acceso-st_error']; ?></option>          <?php do {?>
                        <option value="<?php echo $row_estado['id']; ?>"><?php echo $row_estado['name']; ?></option>
                        <?php } while ($row_estado mysql_fetch_assoc($estado));
                                
$rows mysql_num_rows($estado);
                                if(
$rows 0) {
                                
mysql_data_seek($estado0);
                                
$row_estado mysql_fetch_assoc($estado);} ?>
</select>
<select name="city" class="cities" id="cityId">
<option value="">Select City</option>
<option value="0" selected="selected"><?php echo $TEXT['acceso-ci_error']; ?></option>          <?php do {?>
                        <option value="<?php echo $row_ciudad['id']?>"><?php echo $row_ciudad['name']?></option>
                        <?php } while ($row_ciudad mysql_fetch_assoc($ciudad));
                                
$rows mysql_num_rows($ciudad);
                                if(
$rows 0) {
                                
mysql_data_seek($ciudad0);
                                
$row_ciudad mysql_fetch_assoc($ciudad);} ?>
</select>
<?php foreach($_POST as $nombre_campo => $valor){
   
$asignacion "\$" $nombre_campo "='" $valor "';";
   eval(
$asignacion); }  ?>
</body>
</html>
<?php mysql_free_result($pais);
mysql_free_result($estado);
mysql_free_result($ciudad);?>
Código MySQL:
Ver original
  1. CREATE TABLE IF NOT EXISTS `countries` (
  2.   `id` int(11) NOT NULL AUTO_INCREMENT,
  3.   `sortname` varchar(3) NOT NULL,
  4.   `name` varchar(150) NOT NULL,
  5.   PRIMARY KEY (`id`)

Código MySQL:
Ver original
  1. CREATE TABLE IF NOT EXISTS `states` (
  2.   `id` int(11) NOT NULL AUTO_INCREMENT,
  3.   `name` varchar(30) NOT NULL,
  4.   `country_id` int(11) NOT NULL DEFAULT '1',
  5.   PRIMARY KEY (`id`)

Código MySQL:
Ver original
  1. CREATE TABLE IF NOT EXISTS `cities` (
  2.   `id` int(11) NOT NULL AUTO_INCREMENT,
  3.   `name` varchar(30) NOT NULL,
  4.   `state_id` int(11) NOT NULL,
  5.   PRIMARY KEY (`id`)

combo_dependientes.js
Código Javascript:
Ver original
  1. function ajaxCall() {
  2.         this.send = function(data, url, method, success, type) {
  3.           type = type||'json';
  4.           var successRes = function(data) {
  5.               success(data);
  6.           }
  7.           var errorRes = function(e) {
  8.               console.log(e);
  9.               alert("Error found \nError Code: "+e.status+" \nError Message: "+e.statusText);
  10.               $('#loader').modal('hide');
  11.           }
  12.             $.ajax({
  13.                 url: url,
  14.                 type: method,
  15.                 data: data,
  16.                 success: successRes,
  17.                 error: errorRes,
  18.                 dataType: type,
  19.                 timeout: 60000
  20.             });
  21.           }
  22.         }
  23. function locationInfo() {
  24.     var rootUrl = "http://lab.iamrohit.in/php_ajax_country_state_city_dropdown/api.php";
  25.     var call = new ajaxCall();
  26.     this.getCities = function(id) {
  27.         $(".cities option:gt(0)").remove();
  28.         var url = rootUrl+'?type=getCities&stateId=' + id;
  29.         var method = "post";
  30.         var data = {};
  31.         $('.cities').find("option:eq(0)").html("Please wait..");
  32.         call.send(data, url, method, function(data) {
  33.             $('.cities').find("option:eq(0)").html("Select City");
  34.             if(data.tp == 1){
  35.                 $.each(data['result'], function(key, val) {
  36.                     var option = $('<option />');
  37.                     option.attr('value', val).text(val);
  38.                      option.attr('cityid', key);
  39.                     $('.cities').append(option);
  40.                 });
  41.                 $(".cities").prop("disabled",false);
  42.             }
  43.             else{
  44.                  alert(data.msg);
  45.             }
  46.         });
  47.     };
  48.     this.getStates = function(id) {
  49.         $(".states option:gt(0)").remove();
  50.         $(".cities option:gt(0)").remove();
  51.         var url = rootUrl+'?type=getStates&countryId=' + id;
  52.         var method = "post";
  53.         var data = {};
  54.         $('.states').find("option:eq(0)").html("Please wait..");
  55.         call.send(data, url, method, function(data) {
  56.             $('.states').find("option:eq(0)").html("Select State");
  57.             if(data.tp == 1){
  58.                 $.each(data['result'], function(key, val) {
  59.                     var option = $('<option />');
  60.                         option.attr('value', val).text(val);
  61.                         option.attr('stateid', key);
  62.                     $('.states').append(option);
  63.                 });
  64.                 $(".states").prop("disabled",false);
  65.             }
  66.             else{
  67.                 alert(data.msg);
  68.             }
  69.         });
  70.     };
  71.     this.getCountries = function() {
  72.         var url = rootUrl+'?type=getCountries';
  73.         var method = "post";
  74.         var data = {};
  75.         $('.countries').find("option:eq(0)").html("Please wait..");
  76.         call.send(data, url, method, function(data) {
  77.             $('.countries').find("option:eq(0)").html("Select Country");
  78.             console.log(data);
  79.             if(data.tp == 1){
  80.                 $.each(data['result'], function(key, val) {
  81.                     var option = $('<option />');
  82.                     option.attr('value', val).text(val);
  83.                      option.attr('countryid', key);
  84.                     $('.countries').append(option);
  85.                 });
  86.                 $(".countries").prop("disabled",false);
  87.             }
  88.             else{
  89.                 alert(data.msg);
  90.             }
  91.         });
  92.     };
  93. }
  94. $(function() {
  95. var loc = new locationInfo();
  96. loc.getCountries();
  97.  $(".countries").on("change", function(ev) {
  98.         var countryId = $("option:selected", this).attr('countryid');
  99.         if(countryId != ''){
  100.         loc.getStates(countryId);
  101.         }
  102.         else{
  103.             $(".states option:gt(0)").remove();
  104.         }
  105.     });
  106.  $(".states").on("change", function(ev) {
  107.         var stateId = $("option:selected", this).attr('stateid');
  108.         if(stateId != ''){
  109.         loc.getCities(stateId);
  110.         }
  111.         else{
  112.             $(".cities option:gt(0)").remove();
  113.         }
  114.     });
  115. });
  #2 (permalink)  
Antiguo 06/04/2016, 13:17
 
Fecha de Ingreso: marzo-2016
Mensajes: 6
Antigüedad: 8 años, 1 mes
Puntos: 0
Respuesta: Tres select dependientes que no funcionan

Nadie puede ayudarme?
  #3 (permalink)  
Antiguo 06/04/2016, 15:03
 
Fecha de Ingreso: enero-2014
Ubicación: Navarra
Mensajes: 94
Antigüedad: 10 años, 4 meses
Puntos: 18
Respuesta: Tres select dependientes que no funcionan

Hola.

Que error te da ?

mirando el codigo por encima el archivo combo_dependientes.js deberia de cargar despues de jquery.

Tambien el codigo js lo meteria dentro de :

Código Javascript:
Ver original
  1. $(document).ready(function(){
  2. // aqui el codigo
  3. });

para que este funcione cuando cargue el DOM y los elementos.

saludos.
  #4 (permalink)  
Antiguo 06/04/2016, 15:10
 
Fecha de Ingreso: junio-2011
Mensajes: 289
Antigüedad: 12 años, 10 meses
Puntos: 15
Respuesta: Tres select dependientes que no funcionan

Lo que pasa es que está un poco desordenado tu código, entonces cuando alguien entra y ve todo eso o no tiene ganas o no tiene tiempo de hacer el seguimiento completo.

Tampoco tienes descripción del proceso o algo que de pistas de que puede ser, lo que obliga a leer todo.

Te recomendaría implementar modelos MVC o separar las capas.



Ahora lo que dice sintel_1 es correcto, debes cargar primero JQUERY antes que tus librerías.

Etiquetas: dependientes, funcionan, select, tres
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 22:19.