Ir para conteúdo

POWERED BY:

Arquivado

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

George Cruz

3 Combox dinamicos

Recommended Posts

gente to tentando fazer um formulario dinamico com um script que achei na net funfar aqui mais ta f*** alguem me ajuda ai, o primeiro select vai de boa agora o segundo nem com reza brava já tentei de tudo.

 

index.php

<?php require_once('Connections/connect.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_connect, $connect);
$query_MARCA = "SELECT DISTINCT MARCA FROM REFERENCIAS ORDER BY MARCA ASC";
$MARCA = mysql_query($query_MARCA, $connect) or die(mysql_error());
$row_MARCA = mysql_fetch_assoc($MARCA);
$totalRows_MARCA = mysql_num_rows($MARCA);

mysql_select_db($database_connect, $connect);
$query_CODIGO = "SELECT CODIGO FROM REFERENCIAS";
$CODIGO = mysql_query($query_CODIGO, $connect) or die(mysql_error());
$row_CODIGO = mysql_fetch_assoc($CODIGO);
$totalRows_CODIGO = mysql_num_rows($CODIGO);

mysql_select_db($database_connect, $connect);
$query_Recordset1 = "SELECT RELECO FROM REFERENCIAS";
$Recordset1 = mysql_query($query_Recordset1, $connect) or die(mysql_error());
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
$totalRows_Recordset1 = mysql_num_rows($Recordset1);
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Cross Referencia | Comat Releco do Brasil</title>
<script language="javascript">
/* Busca do primeiro para o segundo select */
function list_dados( valor )
{
http.open("GET", "result.php?id=" + valor, true);
http.onreadystatechange = handleHttpResponse1;
http.send(null);
}

function handleHttpResponse1()
{
campo_select = document.forms[0].subcategoria;
if (http.readyState == 4) {
campo_select.options.length = 0;
results = http.responseText.split(",");
for( i = 0; i < results.length; i++ )
{
string = results[i].split( "|" );
campo_select.options[i] = new Option( string[0], string[1] );
}
}
}
function handleHttpResponse2()
{
campo_select2 = document.forms[0].subsubcategoria;
if (http.readyState == 4) {
campo_select2.options.length = 0;
results2 = http.responseText.split(",");
for( i = 0; i < results2.length; i++ )
{
string2 = results2[i].split( "|" );
campo_select2.options[i] = new Option( string2[0], string2[1] );
}
}
}
function getHTTPObject() {
var req;
try {
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
if (req.readyState == null) {
req.readyState = 1;
req.addEventListener("load", function () {
req.readyState = 4;

if (typeof req.onreadystatechange == "function")
req.onreadystatechange();
}, false);
}
return req;
}

if (window.ActiveXObject) {

var prefixes = ["MSXML2", "Microsoft", "MSXML", "MSXML3"];

for (var i = 0; i < prefixes.length; i++) {
try {
req = new ActiveXObject(prefixes[i] + ".XmlHttp");
return req;
} catch (ex) {};

}
}
} catch (ex) {}
alert("XmlHttp Objects not supported by client browser");
}
var http = getHTTPObject();
// Logo após fazer a verificação, é chamada a função e passada
// o valor à variável global http.


/* Busca do segundo para o terceiro select */
function list_dados2( valor )
{
http.open("GET", "result2.php?id2=" + valor, true);
http.onreadystatechange = handleHttpResponse2;
http.send(null);
}
</script>
<script src="SpryAssets/SpryValidationSelect.js" type="text/javascript"></script>
<link href="SpryAssets/SpryValidationSelect.css" rel="stylesheet" type="text/css">
</head>

<body>
<form id="form1" name="form1" method="post" action="">
 <p><span id="spryselect1">
   <label>
     <select name="categoria" id="categoria" accesskey="1" tabindex="1" onChange="javascript:list_dados(this.value);">
       <option value="0">Selecione o Fabricante</option>
       <?php
do {  
?>
       <option value="<?php echo $row_MARCA['MARCA']?>"><?php echo $row_MARCA['MARCA']?></option>
       <?php
} while ($row_MARCA = mysql_fetch_assoc($MARCA));
 $rows = mysql_num_rows($MARCA);
 if($rows > 0) {
     mysql_data_seek($MARCA, 0);
  $row_MARCA = mysql_fetch_assoc($MARCA);
 }
?>
     </select>
   </label>
 <span class="selectInvalidMsg">Please select a valid item.</span><span class="selectRequiredMsg">Please select an item.</span></span></p>
 <p><span id="spryselect2">
   <label>
     <select name="subcategoria" id="subcategoria" accesskey="2" tabindex="2" onChange="javascript:list_dados2(this.value)>
       <?php
do {  
?>
       <option value="<?php echo $row_CODIGO['CODIGO']?>">
       <option value="0">Escolha primeiro o Fabricante</option>
       <?php echo $row_CODIGO['CODIGO']?>
       <?php
} while ($row_CODIGO = mysql_fetch_assoc($CODIGO));
 $rows = mysql_num_rows($CODIGO);
 if($rows > 0) {
     mysql_data_seek($CODIGO, 0);
  $row_CODIGO = mysql_fetch_assoc($CODIGO);
 }
?>
     </select>
   </label>
 <span class="selectInvalidMsg">Please select a valid item.</span><span class="selectRequiredMsg">Please select an item.</span></span></p>
 <p>
   <label>
     <select name="subsubcategoria" id="subsubcategoria" accesskey="3" tabindex="3">
       <option value="0">Escolha primeiro o Código</option>
     </select>
   </label>
 </p>
</form>
<script type="text/javascript">
<!--
var spryselect1 = new Spry.Widget.ValidationSelect("spryselect1", {validateOn:["change", "blur"], invalidValue:"0"});
var spryselect2 = new Spry.Widget.ValidationSelect("spryselect2", {validateOn:["change", "blur"], invalidValue:"0"});
//-->
</script>
</body>
</html>
<?php
mysql_free_result($MARCA);

mysql_free_result($CODIGO);

mysql_free_result($Recordset1);
?>

 

result.php

<?php
//Adicionado para não quebrar acentuação.
header("Content-Type: text/html; charset=iso-8859-1");

//Faz o controle de cache.
$gmtDate = gmdate("D, d M Y H:i:s");
header("Expires: {$gmtDate} GMT");
header("Last-Modified: {$gmtDate} GMT");
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");

$server = "*************";
$user = "comatrelec";
$password = "*************";
$database = "comatrelec";
$connect = mysql_connect($server, $user, $password) or die ("Não foi possivel conectar ao banco de dados");
mysql_select_db($database, $connect);
$linha = "";
// Guardando o id passado pelo form select
// Trim remove os espaços no inicio e final
// addslashes Retorna uma string com barras invertidas antes de caracteres 
// que precisam ser escapados para serem escapados em query a banco de dados
$categoria = addslashes(trim($_GET["id"])); 
// Fazendo nosso selec para todas subcategorias que pertencem à categoria presente 
// na variavel $categoria acima
$consulta = mysql_query("SELECT * FROM  `REFERENCIAS`                    
	WHERE MARCA = '$categoria'  
	ORDER BY CODIGO" ); 
while( $row = mysql_fetch_assoc($consulta) ){
       // subcategoria será apresentada da forma "NOME|CODIGO,..."
       // Maneira a ser tratada no JavaScript
       // Vale lembrar que estamos contatenando o "nome" com a "|" com o "codigo" e com a ","  
       $linha .=  $row["CODIGO"] . "|" . $row["MARCA"] . ","; 
}
//Retira a última vírgula para não vir registro em branco.
$linha = substr($linha,0,(strlen($linha)-1));
echo $linha;
?>

 

result2.php

 

<?php
//Adicionado para não quebrar acentuação.
header("Content-Type: text/html; charset=iso-8859-1");

//Faz o controle de cache.
$gmtDate = gmdate("D, d M Y H:i:s");
header("Expires: {$gmtDate} GMT");
header("Last-Modified: {$gmtDate} GMT");
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");

$server = "***************";
$user = "comatrelec";
$password = "*****************";
$database = "comatrelec";
$connect = mysql_connect($server, $user, $password) or die ("Não foi possivel conectar ao banco de dados");
mysql_select_db($database, $connect);
$linha = "";
// Guardando o id passado pelo form select
// Trim remove os espaços no inicio e final
// addslashes Retorna uma string com barras invertidas antes de caracteres 
// que precisam ser escapados para serem escapados em query a banco de dados
$subcategoria = addslashes(trim($_GET["id2"])); 
// Fazendo nosso selec para todas subcategorias que pertencem à categoria presente 
// na variavel $categoria acima
$consulta = mysql_query("SELECT * FROM  `REFERENCIAS`                    
	WHERE CODIGO = '$subcategoria'  
	ORDER BY CODIGO" ); 
while( $row = mysql_fetch_assoc($consulta) ){
       // subcategoria será apresentada da forma "NOME|CODIGO,..."
       // Maneira a ser tratada no JavaScript
       // Vale lembrar que estamos contatenando o "nome" com a "|" com o "codigo" e com a ","  
       $linha .=  $row["RELECO"] . "|" . $row["CODIGO"] . ","; 
}
//Retira a última vírgula para não vir registro em branco.
$linha = substr($linha,0,(strlen($linha)-1));
echo $linha;
?>

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.