Ir para conteúdo

POWERED BY:

Arquivado

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

Artistic Web

Ajax em 3 níveis com PHP

Recommended Posts

Galera, não estou conseguindo fazer com que funcione o Ajax com o php para que o select seja preenchido dinâmicamente em 3 níveis, no caso categoria, marca, modelo. Abaixo seguem os dados:

 

tabela categorias

id_categoria (numero)

categoria (texto)

 

tabela marcas

id_marca (numero)

marca (texto)

idcategoria (numero)

 

tabela modelos

id_modelo (numero)

idcategoria (numero)

modelo (texto)

idmarca (numero)

categoria (texto)

 

ajax.js

<script>//ESSA FUNÇÃO IRÁ TRAZER O ID DO ESTADO SELECIONADO NA PRIMEITA COMBO PARA PODERMOS PREENCHER A SEGUNDA E TERCEIRA COMBO.function trazdados(){//AQUI "INFORMAMOS" QUE O PRIMEIRA COMBO SERÁ SELECIOANDA E DEPOIS DAMOS UM SPLIT NA BARRA (|) QUE		   //SEPARA OS VALORES QUE ESTÃO NO VALUE DA COMBO1. SE você'S EXIBREM O CÓDIGO FONTE NO BROWSER VERÃO QUE A COMBO1 ESTARÁ ASSIM:// IDESTADO | NOMEESTADO.			   var arr = new String(frm1.categoria.value);			   arr = arr.split('|');//AQUI TRAZEMOS APENAS O ID DE CADA ESTADO QUE FOR SELECIONADO.									   frm1.idcategoria.value = arr[0];						combomarca(); //CHAMA A FUNÇÃO AJAX QUE PREENCHER A COMBO CIDADE, ASSIM QUE É SELECIONADO UM REGISTRO NA COMBO1.						combomodelo(); //CHAMA A FUNÇÃO AJAX QUE PREENCHER A COMBO IMÓVEK, ASSIM QUE É SELECIONADO UM REGISTRO NA COMBO1.		   												  }//AQUI É A FUNÇÃO QUE PREENCHE A COMBO CIDADE.//NÃO VOU ME APROFUNDAR NA EXPLICAÇÃO DESSA FUNÇÃO, JÁ QUE NOS OUTROS ARTIGOS QUE FIZ SOBRE AJAX, TEM A EXPLICAÇÃO SOBRE ELA.//MAS REPAREM NO NOME DA DIV QUE DEMOS AQUI: divcombouf. É O MESMO NOME QUE DEMOS NO ID DAQUELA DIV QUE EXISTE ANTES DA COMBO2 NA PÁGINA.function combomarca(){			   var combocategoria = createXMLHTTP();			   combocategoria.open("post", "marcas.php", true);			   combocategoria.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");			   combocategoria.onreadystatechange=function(){						   if (combocategoria.readyState==4){// abaixo o texto do gerado no arquivo executa.asp e colocado no div									  document.all.divcombocategoria.innerHTML = combocategoria.responseText;}}									  combocategoria.send("idcategoria=" + frm1.idcategoria.value);}//AQUI É A FUNÇÃO QUE SERÁ PREENCHIDA DE ACORDO COM O REGISTRO SELECIONADO NA COMBO1 E NA COMBO2.//A EXPLICAÇÃO DA FUNÇÃO ACIMA VALE PARA ESSA TAMBÉM, JÁ QUE SÃO IGUAIS.function combomodelo(){			   var combomodelo = createXMLHTTP();			   combomodelo.open("post", "modelos.php", true);			   combomodelo.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");			   combomodelo.onreadystatechange=function(){						   if (combomodelo.readyState==4){// abaixo o texto do gerado no arquivo executa.asp e colocado no div									  document.all.divcombomodelo.innerHTML = combomodelo.responseText;}}									  combomodelo.send("idcategoria=" + frm1.idcategoria.value + "&idmarca="+frm1.idmarca.value);			}//NESTA FUNÇÃO IREMOS OBTER O ID DA CIDADE. E PRA QUE PRECISAMOS DELA? PARA PREENCHER A COMBO IMÓVEL.//A COMBO IMÓVEL SÓ TRARÁ REGISTROS DE ACORDO COM O REGISTRO SELECIONADO NA COMBO2.//A EXPLICAÇÃO DA FUNÇÃO TRAZDADOS TAMBÉM VALE PARA ESSA.function dadosmarca(){			   var arr = new String(frm1.marca.value);			   arr = arr.split("|");									   frm1.idmarca.value = arr[3];			   //VEJA QUE CHAMAMOS A FUNÇÃO QUE PREENCHE A COMBO IMÓVEL, DEPOIS QUE UM REGISTRO DA COMBO CIDADE É SELECIONADA.			   combomodelo();}//VOCÊS DEVEM TER REPARADO QUE NAS FUNÇÕES combocidade E comboimovel EXISTEM ESSE CAMINHO OBJETO/NOMEDOARQUIVO.ASP. CERTO?//PORQUE CRIEI? PORQUE SE NO SEU SISTEMA VOCÊ PRECISAR USAR UMA DESSAS COMBOS, VOCÊ CHAMA APENAS O OBJETO.//É COMO TRABALHAR COM ORIENTAÇÃO A OBJETOS.//VEJA A EXPLICAÇÃO DAS PÁGINAS LOGO ABAIXO:</script>

 

marcas.php

<?/******************************************************************// ARQUIVO ...: Monta o XML das Cidades // BY ........: Júlio César Martini	 // DATA ......: 14/03/2006			  /******************************************************************///CONECTA AO MYSQL					 require_once("../ecrm/include/autenticacao.php");require_once("../ecrm/include/mysql.php");		   Connect($user, $passwd, $host);SelectDB($db);//RECEBE PARÃMETRO					 idcategoria = .$_GET("idcategoria")		   //QUERY  $sql = " 	   SELECT 			marcas.marca, marcas.id_marca, categorias.id_categoria		FROM 		   marcas 		INNER JOIN 		   categorias 		ON 		   categorias.id_categoria = marcas.idcategoria 		WHERE 		   marcas.idcategoria = '".$_GET['idcategoria']."'";			//EXECUTA A QUERY			   $sql = mysql_query($sql);	   $row = mysql_num_rows($sql);	//VERIFICA SE VOLTOU ALGO if($row) {				   //XML   $xml  = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n";   $xml .= "<marcas>\n";			         //PERCORRE ARRAY			   for($i=0; $i<$row; $i++) {  	  $codigo	= mysql_result($sql, $i, "id_marca"); 	  $descricao = mysql_result($sql, $i, "marca");	  $xml .= "<marca>\n";	 	  $xml .= "<codigo>".$codigo."</codigo>\n";				  	  $xml .= "<descricao>".$descricao."</descricao>\n";		 	  $xml .= "</marca>\n";	   }//FECHA FOR				       $xml.= "</marcas>\n";      //CABEÇALHO   Header("Content-type: application/xml; charset=iso-8859-1"); }//FECHA IF (row)											   //PRINTA O RESULTADO  echo $xml;			?>

 

modelos.ph

<?/******************************************************************// ARQUIVO ...: Monta o XML das Cidades // BY ........: Júlio César Martini	 // DATA ......: 14/03/2006			  /******************************************************************///CONECTA AO MYSQL					 require_once("../ecrm/include/autenticacao.php");require_once("../ecrm/include/mysql.php");		   Connect($user, $passwd, $host);SelectDB($db);//RECEBE PARÃMETRO					 idmarca = .$_GET("idmarca")		   //QUERY  $sql = " 	   SELECT 			modelos.modelo, modelos.id_modelo, marcas.id_marca		FROM 		   modelos 		INNER JOIN 		   marcas 		ON 		   marcas.id_marca = modelos.idmarca 		WHERE 		   modelos.idmarca = '".$_GET['marca']."'";			//EXECUTA A QUERY			   $sql = mysql_query($sql);	   $row = mysql_num_rows($sql);	//VERIFICA SE VOLTOU ALGO if($row) {				   //XML   $xml  = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n";   $xml .= "<modelos>\n";			         //PERCORRE ARRAY			   for($i=0; $i<$row; $i++) {  	  $codigo	= mysql_result($sql, $i, "id_modelo"); 	  $descricao = mysql_result($sql, $i, "modelo");	  $idmarca = mysql_result($sql, $i, "id_marca");	  $xml .= "<modelo>\n";	 	  $xml .= "<codigo>".$codigo."</codigo>\n";				  	  $xml .= "<descricao>".$descricao."</descricao>\n";	  $xml .= "<descricao>".$idmarca."</descricao>\n";			  $xml .= "</modelo>\n";	   }//FECHA FOR				       $xml.= "</modelos>\n";      //CABEÇALHO   Header("Content-type: application/xml; charset=iso-8859-1"); }//FECHA IF (row)											   //PRINTA O RESULTADO  echo $xml;			?>

 

veiculos_add.php

<?/*************************************************************************** Autor:		 Anderson da Veiga Contact:	   anderson@artisticweb.com.br Copyright:	 Artistic Web. Project:	   E-crm. Version:	   3.0***************************************************************************/ include("../ecrm/include/autenticacao.php");include("../ecrm/include/mysql.php");if($LoadSessions != 1) {		include("../ecrm/include/sessao.php");}CheckSession($sess, usuario, senha);Connect($user, $passwd, $host);SelectDB($db);session_name($sess);session_start();if(!(session_is_registered(auth_email) AND session_is_registered(auth_senha))) {		$stats = 0;} else {		$stats = 1;}$sql = " SELECT * FROM categorias"; 			  $sql = mysql_query($sql);	   $row = mysql_num_rows($sql); $sql2 = "select * from controle_geral";$query2 = mysql_query($sql2);while($row2 = mysql_fetch_array($query2)) {	$titulo = $row2[titulo];}$sql4 = "select * from lojas where usuario='$usuario' and senha='$senha' and status='A'";$query4 = mysql_query($sql4);while($row4 = mysql_fetch_array($query4)) {	$id = $row4[id_loja];}		?><? echo "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>"; ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /><LINK REL="SHORTCUT ICON" href="favicon.ico"> <title><? echo $titulo?></title><link href="../style.css" rel="stylesheet" type="text/css" /><style type="text/css"><!--.style2 {font-size: 12px;	font-family: Verdana, Arial, Helvetica, sans-serif;	color: #FFFFFF;}.style3 {color: #000000}.style4 {font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12px;}--></style><script language="javascript" src="ajax.js"></script></head><body leftmargin="0" rightmargin="0" topmargin="0" bottommargin="0"><table width="779" border="0" align="center" cellpadding="0" cellspacing="0">  <tr>	<td width="850"><object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0" width="779" height="140">	  <param name="movie" value="../img/topo.swf" />	  <param name="quality" value="high" />	  <embed src="../img/topo.swf" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="779" height="140"></embed>	</object></td>  </tr>  <tr>	<td><div align="center">	  <table width="100%" border="0" cellspacing="0" cellpadding="0">		<tr>		  <td bgcolor="#FF7200"><table width="100%" border="0" cellspacing="0" cellpadding="0">			<tr>			  <td width="96%"><div align="right">				<? include("menu_superior.php");?>			  </div></td>			  <td width="4%"> </td>			</tr>		  </table></td>		</tr>		<tr>		  <td valign="top"><div align="center">			  <table width="90%" border="0" align="center" cellpadding="0" cellspacing="0">				<tr>				  <td><div align="center"><br />					  <span class="fonte_nome_revenda">Veículos</span></div></td>				</tr>				<tr>				  <td><form action="veiculos_add_db.php" method="post" enctype="multipart/form-data" name="frm1" id="frm1">					<div id="home"><dir id="formd"> <br />						  <table width="64%" border="0" cellspacing="2" cellpadding="0" align="center">							<tr>							  <td align="left"><div align="right" class="style3">								  <label class="style4" id="labeld">Categoria: </label>															</div></td>							  <td colspan="2" align="left" bgcolor="#FFFFFF"><select name="categoria" id="categoria" onchange="trazdados();">			<option value="0">Selecione a Categoria</option>			<? for($i=0; $i<$row; $i++) { ?>			   <option value="<? echo mysql_result($sql, $i, "categorias.id_categoria"); ?>">			   <? echo mysql_result($sql, $i, "categorias.categoria"); ?></option>			<? } ?>		 </select></td>							</tr>							<tr>							  <td align="left"><div align="right" class="style3">								  <label class="style4" id="labeld">Marca: </label>							  </div></td>							  <td colspan="2" align="left" bgcolor="#FFFFFF"><span id='divcombomarca'>			  <select id="marca" name="marca" onChange="dadosmarca();">											   <option value="0"></option>									 </select>								   </span></td>							</tr>							<tr>							  <td align="left"><div align="right" class="style4">Modelo:</div></td>							  <td colspan="2" align="left" bgcolor="#FFFFFF"> <span id='divcombomodelo'>			  <select id="modelo" name="modelo">				<option value="0"></option>			  </select>								   </span></td>							</tr>														<tr>							  <td align="left"><div align="right" class="style3">								  <label class="style4" id="labeld">Ano:</label>							  </div></td>							  <td colspan="2" align="left" bgcolor="#FFFFFF"><input name="ano" type="text" id="ano" size="4" maxlength="4" /></td>							</tr>							<tr>							  <td align="left"><div align="right" class="style4">Cor:</div></td>							  <td colspan="2" align="left" bgcolor="#FFFFFF"><input name="cor" type="text" id="cor" size="35" maxlength="40" /></td>							</tr>							<tr>							  <td align="left" class="style4"><div align="right">Valor:</div></td>							  <td colspan="2" align="left" bgcolor="#FFFFFF"><input name="valor" type="text" id="valor" size="35" maxlength="40" /></td>							</tr>							<tr>							  <td align="left"><div align="right" class="style3">								  <label class="style4" id="labeld">Combustivel:</label>							  </div></td>							  <td colspan="2" align="left" bgcolor="#FFFFFF"><label>								<span class="fonte_noticias">								<input name="combustivel" type="radio" value="Gasolina" />								G								<input name="combustivel" type="radio" value="alcool" />								A								  <input name="combustivel" type="radio" value="Diesel" />								  D								  <input name="combustivel" type="radio" value="Bicombustível" />								  B</span></label></td>							</tr>							<tr>							  <td align="left"><div align="right" class="style3">								  <label class="style4" id="labeld"></label>							  </div></td>							  <td align="left" bgcolor="#FFFFFF"><label></label></td>							</tr>							<tr>							  <td align="left"><div align="right" class="texto"><span class="style3">								  <label class="style4" id="labeld">OPICIONAIS:</label>							  </span></div></td>							  <td align="left" bgcolor="#FFFFFF"> </td>							</tr>							<tr>							  <td rowspan="4" align="left" class="style2"><div align="right" class="style3"></div></td>							  <td align="left" bgcolor="#FFFFFF" class="fonte_noticias"><span class="texto10">								<input name="ac" type="radio" value="AC/" />								AC								<input name="dh" type="radio" value="DH/" />								DH								<input name="ve" type="radio" value="VE/" />								VE								<input name="te" type="radio" value="TE/" />								TE								<input name="rll" type="radio" value="RLL/" />								RLL </span></td>							</tr>							<tr>							  <td align="left" bgcolor="#FFFFFF" class="fonte_noticias"><span class="texto10">								<input name="cd" type="radio" value="CD/" />								CD								<input name="al" type="radio" value="AL/" />								AL								<input name="abs" type="radio" value="ABS/" />								ABS								<input name="ab" type="radio" value="AB/" />								AB								<input name="ld" type="radio" value="LD/" />								LD </span></td>							</tr>							<tr>							  <td align="left" bgcolor="#FFFFFF" class="fonte_noticias"><span class="texto10">								<input name="ad" type="radio" value="AR DIGITAL/" />								AR DIGITAL								<input name="acs" type="radio" value="ACESSÓRIOS/" />								ACESSÓRIOS </span></td>							</tr>							<tr>							  <td align="left" bgcolor="#FFFFFF" class="fonte_noticias"><span class="texto10">								<input name="ud" type="radio" value="ÚNICO DONO/" />								ÚNICO DONO								<input name="cpt" type="radio" value="COMPLETO" />								COMPLETO </span></td>							</tr>							<tr>							  <td width="27%" align="left"><div align="right" class="style3">								  <label class="style4" id="labeld">Foto 1:</label>							  </div></td>							  <td width="73%" align="left" bgcolor="#FFFFFF"><input name="foto_um" type="file" id="foto_um" />							  </td>							</tr>							<tr>							  <td width="27%" align="left"><div align="right"><span class="style4">Foto 2:</span></div></td>							  <td align="left" bgcolor="#FFFFFF"><input name="foto_dois" type="file" id="foto_dois" /></td>							</tr>							<tr>							  <td width="27%" align="left"><div align="right"><span class="style4">Foto 3:</span></div></td>							  <td align="left" bgcolor="#FFFFFF"><input name="foto_tres" type="file" id="foto_tres" /></td>							</tr>							<tr>							  <td width="27%" align="left"><div align="right"><span class="style4">Foto 4:</span></div></td>							  <td align="left" bgcolor="#FFFFFF"><input name="foto_quatro" type="file" id="foto_quatro" /></td>							</tr>						  </table>					  </dir><dir id="formd">					  <table width="47%" border="0" cellspacing="6" cellpadding="0" align="center">						<tr>						  <td width="25%" align="right"></td>						  <td width="50%" align="center"><input name="submit" type="submit" class="box_cadastro" title="Cadastrar Veículo" value="Cadastrar"/></td>						  <td width="25%" align="right"></td>						</tr>					  </table>					  </dir></div><input type="hidden" name="idcategoria" id="idcategoria" value="<? $id_categoria ?>" size="3"><input type="hidden" name="idmarca" id="idmarca" value="<? $id_marca ?>" size="3"><input type="hidden" name="idmodelo" id="idmodelo" value="<? $id_modelo ?>" size="3">				  </form></td>				</tr>			  </table>			  <p> </p>		  </div></td>		</tr>	  </table>	</div></td>  </tr>    <tr>	<td><label><img src="../img/bottom.gif" width="779" height="48" border="0" usemap="#Map" /></label></td>  </tr></table><map name="Map" id="Map"><area shape="rect" coords="680,3,762,47" href="http://www.artisticweb.com.br" alt="Artistic Web - Soluções Internet" /></map></body></html>

 

Se alguém puder me ajudar ficarei muito grato.

 

Se quiserem ver os arquivos rodando acessem http://www.classifiweb.com.br/revendas/login.php

 

Login: stadtcar

senha: 123456

 

Valew

Compartilhar este post


Link para o post
Compartilhar em outros sites

Estou precisando dessa mesma ajuda,

entrei no seu site e vi que você conseguiu fazer o carregamento de dados em 3 níveis.

 

Você pode me ajudar?

 

Estou tentando a um tempão e não estou conseguindo.

 

Voce pode postar aqui seu script? de como voce fez?

Compartilhar este post


Link para o post
Compartilhar em outros sites

Bom dia,

 

agora estou um pouco ocupado, mas sem problema, a noite te mando o source e as explicações.

 

Anderson

 

Estou precisando dessa mesma ajuda,

entrei no seu site e vi que você conseguiu fazer o carregamento de dados em 3 níveis.

 

Você pode me ajudar?

 

Estou tentando a um tempão e não estou conseguindo.

 

Voce pode postar aqui seu script? de como voce fez?

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.