Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

Élton F. Moraes

[Resolvido] Problema ao carregar combo box dinâmica com PHP, MySQ

Recommended Posts

Boa tarde pessoal. Estou com um problema chato no Ajax. Criei a combo box de estados e cidades. A de estado funciona direitinho, carreguei pelo banco de dados e aparece sem problemas. Fiz um esquema de XML para as cidades, rodei só o XML e funciona a sintaxe. O problema que eu tenho quase 100% de certeza que é no Ajax, aqui está o código:

 

var HttpReq = null;
var dest_combo = null;

function ajaxComboBox(url, comboBox) {
dest_combo = comboBox;
var index = document.getElementById('sel_state').selectedIndex;
var sigla = document.getElementById('sel_state').options[index].getAttribute('value');
url = url + '?uf=' + sigla;

if (document.getElementById) { // Verifica se o Browser suporta DHTML.
	if (window.XMLHttpRequest) {
		HttpReq = new XMLHttpRequest();
		HttpReq.onreadystatechange = XMLHttpRequestChange;
		HttpReq.open("GET", url, true);
		HttpReq.send(null);
	} else if (window.ActiveXObject) {
		HttpReq = new ActiveXObject("Microsoft.XMLHTTP");
		if (HttpReq) {
			HttpReq.onreadystatechange = XMLHttpRequestChange;
			HttpReq.open("GET", url, true);
			HttpReq.send();
		}
	}
}
}

function XMLHttpRequestChange() {
if (HttpReq.readyState == 4 && HttpReq.status == 200) {
	var result = HttpReq.responseXML;
	var cities = result.getElementsByTagName("nome");
	document.getElementById('dest_combo').innerHTML = "";
	for (var i = 0; i < cities.length; i++) {
		new_option = create_option(cities[i]);
		document.getElementById('dest_combo').appendChild(new_option);
	}
}
}

function create_option(cities) {
var new_option = document.createElement("option");
var text = document.createTextNode(cities.childNodes[0].data);
new_option.setAttribute("value", cities.getAttribute("id"));
new_option.appendChild(text); // Adiciona o texto a OPTION.
return new_option; // Retorna a nova OPTION.
}

 

Já tentei fazer umas alterações, mas não obtive sucesso. Se precisar do código PHP ou o XML, só pedir que eu coloco aqui.

 

Obrigado!

 

Só complementando: quando escolho um estado, simplesmente a combo de cidades não carrega.

Vou passar os outros códigos pra ficar melhor.

 

XML:

 

<?php
require_once ("conexao.php");
header("Content-type: text/xml; charset=ISO-8859-1");
   print '<?xml version="1.0" encoding="ISO-8859-1"?>';
?>

<cidades>
<?php
	try {
		$con = conexao();
	} catch (Exception $e) {
		$msg = $e->getMessage();
	}

	$result2 = $con->query("SELECT c.id, c.uf, c.nome FROM tb_cidades c
							WHERE c.uf = '{$_GET['uf']}' ORDER BY c.nome");

	while ($row2 = mysqli_fetch_array($result2, MYSQL_NUM)) {
		printf("<nome id=\"%d\">%s</nome>\n", $row2[0],$row2[2]);
	}
?>
</cidades>

 

 

 

PHP/HTML (só a parte que importa):

 

<?php
require_once ("conexao.php");

try {
	$con = conexao();
} catch (Exception $e) {
	$msg = $e->getMessage();
}

$result = $con->query("SELECT e.id, e.uf, e.nome FROM tb_estados e ORDER BY e.nome");
?>

<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
	<title>User Registration</title>
	<script type="text/javascript" src="cities.js"></script>
...
...
...
</head>
<body>
    <form id="form1" method="post" name="form1">
    	<table id="table1" cellspacing="5" cellpadding="1">
<tr>
    			<td height="30"><label>State </label></td>
    			<td>
    				<select name="sel_state" id="sel_state" onchange="ajaxComboBox('cities.php','sel_city');">
    					<option value="0">Selecione um estado</option>
    				<?php
    					while ($row = mysqli_fetch_array($result)) {
    						$uf = $row[1];
    						$name = $row[2];
    				?>
    					<option value="<?php print $uf?>"><?php print $name?></option>
    				<?php } ?>
    				</select>
    			</td>
    			<td><label>City </label></td>
    			<td>
    				<select name="sel_city" id="sel_city">
    					<option>Primeiro selecione um estado</option>
    				</select>
    			</td>
    		</tr>
...
...
...
    	</table>
    </form>
</body>
</html>

Compartilhar este post


Link para o post
Compartilhar em outros sites

seguinte, acessa diretamente:

 

cities.php?uf=sp

 

ou outro UF que vá te retornar algum resultado.

Veja se aparece erros ou o xml. Corrija.

 

exemplo com jQuery: (lendo jSON)

http://forum.imasters.com.br/topic/365795-combos-dependentes-ajax-jquery/

Compartilhar este post


Link para o post
Compartilhar em outros sites

Seu combo cidade tem id "sel_city" e em sua função você colocou: "dest_combo"

document.getElementById('dest_combo').appendChild(new_option);

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.