Ver Mensaje Individual
  #1 (permalink)  
Antiguo 27/12/2010, 11:33
Avatar de javiertroya
javiertroya
 
Fecha de Ingreso: mayo-2009
Ubicación: Valencia
Mensajes: 15
Antigüedad: 15 años
Puntos: 2
Información Selects dinamicos con Ajax

Hoy realizaremos el mismo ejercicio de selects dinamicos pero ahora sin necesidad de que se refresque la pagina usando Ajax.

Requisitos:
Apache - PHP - MySQL
Librería ez_sql
Conocimiento avanzado de PHPOO
Interpretación del código

Descarguemos la libreria de base de datos http://justinvincent.com/wp-content/uploads/2010/10/ez_sql_2.05.zip

Ahora creemos la siguiente estructura en nuestro servidor
www/
php/
ez_sql/
selects.php
db.php
javascript/
ajax.js
selects.js
index.php

Ahora llenamos los archivos con contenido:

index.php
Código HTML:
<html> 
<head> 
 <title>Selects dinamicos AJAX</title> 
 <script>baseurl = 'http://misitio.com';</script> 
 <script language="javascript" type="text/javascript" src="javascript/ajax.js"></script> 
 <script language="javascript" type="text/javascript" src="javascript/selects.js"></script> 
</head> 
<body> 
 <form> 
  <label>Selecciona el estado</label> 
  <div> 
  <select name="pais" id="pais" onchange="cambiar_select('cambiaCiudad', 'ciudad', 'ciudad', 'ciudad', 'cambiar_ciudades', this.value, '100%', false)">
   <option>Seleccione</option> 
<?php 
require_once('php/db.php'); 
if($paises = $db->get_results('select pais from paises order by pais asc')): 

 foreach($paises as $row): 
  echo '<option value="'.$row->pais.'">'.$row->pais.'</option>'; 
 endforeach; 

else: 

 echo '<option>No existen paises</option>'; 

endif; 
?> 
  </select> 
  </div> 
  <label>Ciudad</label> 
  <div id="cambiaCiudad"><select><option>Selecciona pais</option></select></div> 
 </form> 
</body> 

Ahora llenamos los archivos javascript

ajax.js

Código HTML:
function newAjax() 
{ 
  var xmlHttp=null; 
  if (window.ActiveXObject)  
    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); 
  else  
    if (window.XMLHttpRequest)  
      xmlHttp = new XMLHttpRequest(); 
  return xmlHttp; 
} 

function addEvent(elemento,nomevento,funcion,captura) 
{ 
  if (elemento.attachEvent) 
  { 
    elemento.attachEvent('on'+nomevento,funcion); 
    return true; 
  } 
  else   
    if (elemento.addEventListener) 
    { 
      elemento.addEventListener(nomevento,funcion,captura); 
      return true; 
    } 
    else 
      return false; 
}

selects.js

Código HTML:
function cambiar_select(divId, tagName, selectName, selectId, funcion, parametro, Width, AddEvent)
{ 
    url = baseurl+'php/selects.php?funcion='+funcion+'&parametro='+parametro+'&tagName='+tagName; 
    ajax = newAjax(); 
    ajax.onreadystatechange = function() 
    { 
        var div = document.getElementById(divId); 
        div.innerHTML = ''; 
         
        if(ajax.readyState == 4) 
        { 
            var xml = ajax.responseXML; 
            var opt = xml.getElementsByTagName(tagName); 
             
            var select = document.createElement('select'); 
            select.name = selectName; 
            select.id = selectId; 
            select.style.width = Width; 
             
            var seleccione = document.createElement('option'); 
            var texto = document.createTextNode('Seleccione'); 
            seleccione.appendChild(texto); 
            seleccione.value = 'seleccione'; 
            select.appendChild(seleccione); 
            div.appendChild(select); 
             
            if(parametro != 'seleccione') 
            { 
                for(i=0;i<opt.length;i++) 
                { 
                    var option = document.createElement('option'); 
                    var text = document.createTextNode(opt[i].firstChild.nodeValue); 
                    option.appendChild(text); 
                    select.appendChild(option); 
                } 
                if(AddEvent == true) 
                { 
                    addUrl = baseurl+'php/php_selects.php?funcion='+funcion+'_addEvent&parametro=NULL&tagName=NULL'; 
                    addEv = newAjax(); 
                    addEv.onreadystatechange = function() 
                    { 
                        if(addEv.readyState == 4) 
                        { 
                            funcion = addEv.responseText; 
                        } 
                    } 
                    addEv.open('GET',addUrl,true); 
                    addEv.send(null); 
                    addEvent(select,'change',function(){ eval(funcion); },false); 
                } 
            } 
        } 
        else 
        { 
            div.innerHTML = '<img src="'+baseurl+'images/cargando.gif" />'; 
        } 
    } 
     
    ajax.open('GET',url, true); 
    ajax.send(null); 
}

Procedemos a llenar los archivos en la carpeta php

db.php

Código PHP:
require_once('ez_sql/shared/ez_sql_core.php'); 
require_once(
'ez_sql/mysql/ez_sql_mysql.php'); 
$db = new ezSQL_mysql('database_user','database_password','select_database','database_host'); 
Y ahora el archivo mas importante porque es el que generará las respuestas XML necesarias para que el script corra perfectamente

selects.php

Código PHP:
require("db.php"); 
if($_REQUEST) 

    $funcion = $_REQUEST["funcion"]; 
    $parametro = $_REQUEST["parametro"]; 
    $tagName = $_REQUEST["tagName"]; 
    if(function_exists($funcion)) 
    { 
        echo $funcion($parametro); 
    } 
    else 
    { 
        $xml="<?xml version="1.0"?>n"; 
            $xml.="<marco>n"; 
                $xml.="<".$tagName.">Error de conexion</".$tagName.">"; 
            $xml.="</marco>"; 
        header('Content-Type: text/xml'); 
        echo $xml; 
    } 


function cambiar_ciudades($pais) 

    global $db,$tagName; 
    $xml="<?xml version="1.0"?>n"; 
    $xml.="<marco>n"; 
    if($ciudades = $db->get_results('select ciudad from ciudades where pais = "'.$pais.'"'))
    { 
        foreach($ciudades as $row) 
        { 
            $xml.= "<".$tagName.">".$row->ciudad."</".$tagName.">n"; 
        } 
    } 
    else 
    { 
        $xml.="<".$tagName.">No existen ciudades</".$tagName.">"; 
    } 
    $xml.="</marco>n"; 
    header('Content-Type: text/xml'); 
    return $xml; 

//FIN FUNCION

Esta es la estructura de la base de datos


Código PHP:
CREATE TABLE IF NOT EXISTS `paises` ( 
  `
idint(2NOT NULL AUTO_INCREMENT
  `
estadovarchar(100COLLATE utf8_spanish_ci NOT NULL
  
PRIMARY KEY (`id`) 
ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci AUTO_INCREMENT=

INSERT INTO `estados` (`id`, `estado`) VALUES 
(1'Venezuela'), 
(
2'Colombia'), 
(
3'Ecuador'), 
(
4'Argentina'); 


CREATE TABLE IF NOT EXISTS `ciudades` ( 
  `
idint(3NOT NULL AUTO_INCREMENT
  `
paisvarchar(100COLLATE utf8_spanish_ci NOT NULL
  `
ciudadvarchar(150COLLATE utf8_spanish_ci NOT NULL
  
PRIMARY KEY (`id`) 
ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci AUTO_INCREMENT=

INSERT INTO `ciudades` (`id`, `estado`, `ciudad`) VALUES 
(1'Venzuela''Valencia'), 
(
2'Venezuela''Caracas'), 
(
3'Colombia''Bogota'), 
(
4'Argentina''Buenos Aires'), 
(
5'Argentina''Andalucia'), 
(
6'Colombia''Cali'); 


Y eso debería hacer todo para que los selects cambien dependiendo del país por supuesto muchas gracias por leer... Saludos!