Jump to content

Recommended Posts

Posted

Boas pessoal,

Estou aqui com um problema e já me estou a passar com isto. Se alguém me puder agradeço desde já.

Então é assim, estou a construir um formulário para o registo de empresas num directório.

Problema, estou a usar Ajax em duas partes do registo (distrito+cidade e categoria+subcategoria), ao escolher o distrito ele muda-me a combo da subcategoria.

Código HTML do Formulário

<tr>

    <td height="25" align="center" valign="middle" class="txt_branco_normal"><strong>Distrito</strong></td>

    <td><label>

<select name="distrito" onChange="javascript:mudar(this.value);">

      <option>Escolher um Distrito</option>

      <?php

  // INCLUSÃO DO ARQUIVOS DE CONFIGURAÇÃO E CONEXÃO COM O BANCO DE DADOS

  include "config.inc.php";

  //

  $sql = "SELECT * FROM empresas_distritos ORDER BY titulo ASC";

  $resultado = mysql_query($sql) or die ("Problema na Consulta");

    while($linha = mysql_fetch_array($resultado))

  {

?>

      <option value="<?=$linha['id'] ?>">

        <?=$linha['titulo'] ?>

        </option>

      <?php

  }

?></select>

    </label></td>

  </tr>

<tr>

    <td height="25" align="center" valign="middle" class="txt_branco_normal"><strong>Categoria</strong></td>

    <td><label>

<select name="categoria" onChange="javascript:mudar(this.value);">

      <option>Escolher uma Categoria</option>

      <?php

  // INCLUSÃO DO ARQUIVOS DE CONFIGURAÇÃO E CONEXÃO COM O BANCO DE DADOS

  include "config.inc.php";

  //

  $sql2 = "SELECT * FROM empresas_categorias ORDER BY titulo ASC";

  $resultado2 = mysql_query($sql2) or die ("Problema na Consulta");

    while($linha2 = mysql_fetch_array($resultado2))

  {

?>

      <option value="<?=$linha2['id'] ?>">

        <?=$linha2['titulo'] ?>

        </option>

      <?php

  }

?></select>

    </label></td>

  </tr>

  <tr>

    <td height="25" align="center" valign="middle" class="txt_branco_normal"><strong>Sub-Categoria</strong></td>

    <td><div id="mostraSubCategoria">

      <select name="subcategoria">

        <option></option>

      </select>

    </div></td>

  </tr>

Cidades.js

//CRIA A VARIÁVEL RETORNO

var retorno;

function CarregaArquivo(url,valor)

{

    retorno = null;

//CRIA O OBJETO HttpRequest PARA O RESPECTIVO NAVEGADOR

//Mozilla Fire Fox / Safari ...

//

    if (window.XMLHttpRequest) {

        retorno = new XMLHttpRequest();

//SETA A FUNÇÃO QUE SERÁ CHAMADA QUANDO O AJAX DER UM RETORNO

        retorno.onreadystatechange = processReqChange;

//ABRE A REQUISIÇÃO AJAX, PASSANDO O MÉTODO DE ACESSO, URL E O PARÂMETRO

        retorno.open("GET", url+'?distrito='+valor, true);

//INICIA O TRANSPORTA DOS OBJETOS NA REQUISIÇÃO

        retorno.send(null);

    } else if (window.ActiveXObject) {

//

//IE

//

        retorno = new ActiveXObject("Microsoft.XMLHTTP");

        if (retorno) {

//SETA A FUNÇÃO QUE SERÁ CHAMADA QUANDO O AJAX DER  UM RETORNO

            retorno.onreadystatechange = processReqChange;

    //ABRE A REQUISIÇÃO AJAX, PASSANDO O MÉTODO DE ACESSO, URL E O PARÂMETRO

            retorno.open("GET", url+'?distrito='+valor, true);

//INICIA O TRANSPORTA DOS OBJETOS NA REQUISIÇÃO

            retorno.send();

        }

    }

}

//FUNÇÃO QUE TRATA O RETORNO DO AJAX

function processReqChange()

{

//CASO O STATUS DO AJAX SEJA OK, CHAMA A FUNÇÃO mudar()

//A LISTA COMPLETA DOS VALORES readyState É A SEGUINTE:

//0 (uninitialized)

//1 (a carregar)

//2 (carregado)

//3 (interactivo)

//4 (completo)

    if (retorno.readyState == 4)

{

if(retorno.status == 200)

{

//PROCURA PELA DIV MOSTRACOMBO E INSERE O OBJETO

document.getElementById('mostraCidade').innerHTML = retorno.responseText;

}

else

{

//MOSTRA UM ALERTA AO OBTER UM RETORNO DE OK.

alert("Houve um problema ao obter os dados:\n" + retorno.statusText);

}

  }

}

//FUNÇÃO MUDAR, QUE CHAMA AS INFORMAÇÕES PASSADAS NO PARÂMETRO E CARREGA O ARQUIVO EXTERNO

function mudar(valor)

{

//CARREGA O ARQUIVO EXTERNO DO AJAX

    CarregaArquivo("cidades.php",valor);

}

Cidades.php

  <select name="cidade">

  <option>Escolher uma Cidade</option>

<?php

  // INCLUSÃO DO ARQUIVOS DE CONFIGURAÇÃO E CONEXÃO COM O BANCO DE DADOS

  include "config.inc.php";

  //

  $sql = "SELECT * FROM empresas_cidade WHERE dist_id = '".$_GET['distrito']."' ORDER BY titulo ASC";

  $resultado = mysql_query($sql) or die ("Erro na consulta do banco");

  while($linha = mysql_fetch_array($resultado))

  {

?>  

  <option value="<?=$linha['id'] ?>"><?=$linha['titulo'] ?></option>

<?php

  }

?>

</select>

Empresas.js

//CRIA A VARIÁVEL RETORNO

var retorno;

function CarregaArquivo(url,valor)

{

    retorno = null;

//CRIA O OBJETO HttpRequest PARA O RESPECTIVO NAVEGADOR

//Mozilla Fire Fox / Safari ...

//

    if (window.XMLHttpRequest) {

        retorno = new XMLHttpRequest();

//SETA A FUNÇÃO QUE SERÁ CHAMADA QUANDO O AJAX DER UM RETORNO

        retorno.onreadystatechange = processReqChange;

//ABRE A REQUISIÇÃO AJAX, PASSANDO O MÉTODO DE ACESSO, URL E O PARÂMETRO

        retorno.open("GET", url+'?categoria='+valor, true);

//INICIA O TRANSPORTA DOS OBJETOS NA REQUISIÇÃO

        retorno.send(null);

    } else if (window.ActiveXObject) {

//

//IE

//

        retorno = new ActiveXObject("Microsoft.XMLHTTP");

        if (retorno) {

//SETA A FUNÇÃO QUE SERÁ CHAMADA QUANDO O AJAX DER  UM RETORNO

            retorno.onreadystatechange = processReqChange;

    //ABRE A REQUISIÇÃO AJAX, PASSANDO O MÉTODO DE ACESSO, URL E O PARÂMETRO

            retorno.open("GET", url+'?categoria='+valor, true);

//INICIA O TRANSPORTA DOS OBJETOS NA REQUISIÇÃO

            retorno.send();

        }

    }

}

//FUNÇÃO QUE TRATA O RETORNO DO AJAX

function processReqChange()

{

//CASO O STATUS DO AJAX SEJA OK, CHAMA A FUNÇÃO mudar()

//A LISTA COMPLETA DOS VALORES readyState É A SEGUINTE:

//0 (uninitialized)

//1 (a carregar)

//2 (carregado)

//3 (interactivo)

//4 (completo)

    if (retorno.readyState == 4)

{

if(retorno.status == 200)

{

//PROCURA PELA DIV MOSTRACOMBO E INSERE O OBJETO

document.getElementById('mostraSubCategoria').innerHTML = retorno.responseText;

}

else

{

//MOSTRA UM ALERTA AO OBTER UM RETORNO DE OK.

alert("Houve um problema ao obter os dados:\n" + retorno.statusText);

}

  }

}

//FUNÇÃO MUDAR, QUE CHAMA AS INFORMAÇÕES PASSADAS NO PARÂMETRO E CARREGA O ARQUIVO EXTERNO

function mudar(valor)

{

//CARREGA O ARQUIVO EXTERNO DO AJAX

    CarregaArquivo("empresas.php",valor);

}

Empresas.php

  <select name="subcategoria">

  <option>Escolher uma Sub Categoria</option>

<?php

  // INCLUSÃO DO ARQUIVOS DE CONFIGURAÇÃO E CONEXÃO COM O BANCO DE DADOS

  include "config.inc.php";

  //

  $sql2 = "SELECT * FROM empresas_subcategoria WHERE cat_id = '".$_GET['categoria']."' ORDER BY titulo ASC";

  $resultado2 = mysql_query($sql2) or die ("Erro na consulta do banco");

  while($linha2 = mysql_fetch_array($resultado2))

  {

?>  

  <option value="<?=$linha2['id'] ?>"><?=$linha2['titulo'] ?></option>

<?php

  }

?>

</select>

Eu penso que o problema esteja no facto dos ficheiros cidades.js e empresas.js conterem o mesmo código, mas já tentei mudar o nome das variáveis no empresas.js e mesmo assim nada. 😛

Posted

Desculpa não te ajudar directamente na tua questão ó código ta difícil de ler, mas já experimentas-te jquery? Faz isso rápido e fácil

Fica Bem

O que não tem solução, solucionado esta...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.