← Tutoriais

[AJAX] Pesquisa com auto-sugestão

Lida 5165 vezes

Offline

=IceBurn= 
Membro
Mensagens 897 Gostos 3
Feedback +3

Troféus totais: 32
Trófeus: (Ver todos)
Windows User Level 6 Linux User Mobile User Super Combination Combination Topic Starter Poll Voter Poll Starter Level 5

Boas.

Hoje lá consegui arranjar um tempinho para preparar um novo tutorial.
Já anteriormente 'postei' um tutorial sobre AJAX e hoje vou aprofundar mais um pouco desta potencialidade.

O que proponho é a elaboração de pesquisa com auto-sugestão. A maior parte decerto que já sabe do que se trata, mas para quem ainda não chegou lá, trata-se de ao inserir as palavras chave para uma pesquisa, obter sugestões relacionadas com o que pretendemos pesquisar, ao género do google suggest (http://www.google.com/webhp?complete=1)

Portanto vamos necessitar de 4 ficheiros:
 :arrow: index.html
 :arrow: estilo.css
 :arrow: funcoes.js
 :arrow: sugerir.php

Para começar e para efeitos de teste vamos criar uma tabela na base de dados MySQL com o nome dos 12 meses do ano.
Podem faze-lo facilmente pelo PhpMyAdmin, eis a query:
Código: [Seleccione]
CREATE TABLE `listagem` (
  `id` int(11) NOT NULL auto_increment,
  `mes` char(30) NOT NULL,
  PRIMARY KEY  (`id`)
) TYPE=MyISAM ;

INSERT INTO `listagem` VALUES (1, 'Janeiro');
INSERT INTO `listagem` VALUES (2, 'Fevereiro');
INSERT INTO `listagem` VALUES (3, 'Março');
INSERT INTO `listagem` VALUES (4, 'Abril');
INSERT INTO `listagem` VALUES (5, 'Maio');
INSERT INTO `listagem` VALUES (6, 'Junho');
INSERT INTO `listagem` VALUES (7, 'Julho');
INSERT INTO `listagem` VALUES (8, 'Agosto');
INSERT INTO `listagem` VALUES (9, 'Setembro');
INSERT INTO `listagem` VALUES (10, 'Outubro');
INSERT INTO `listagem` VALUES (11, 'Novembro');
INSERT INTO `listagem` VALUES (12, 'Dezembro');


Agora que temos a nossa tabela preparada vamos configurar o 'motor' no ficheiro sugerir.php
 :arrow: sugerir.php
Código: [Seleccione]
<?php
/**
* @author =IceBurn= &#40;www.jrfreelancer.com&#41;
* @copyright 2007
*/

/* -- -- -- CONFIGURAÇÕES - -- -- -- */

define&#40;"_DB_USER_", "user"&#41;; //-> Username MySQL
define&#40;"_DB_PASS_", "123456"&#41;; //-> Password MySQL
define&#40;"_DB_HOST_", "localhost"&#41;; //-> Host MySQL
define&#40;"_DB_NAME_", "listagem"&#41;; //-> Nome da BD

/* -- -- FIM DAS CONFIGURAÇÕES -- -- */


$link = @mysql_connect&#40;_DB_HOST_, _DB_USER_, _DB_PASS_&#41; or die&#40;"Ligação à Base de Dados Recusada."&#41;;
        
@mysql_select_db&#40;_DB_NAME_, $link&#41; or die&#40;"Não foi possivel seleccionar a Base de Dados."&#41;;

header&#40;"content-type&#58; text/html; charset=iso-8859-1"&#41;;

if&#40;isset&#40;$_GET['q'&#93;&#41;&#41; &#123;

 
$q preg_replace&#40;"/[^a-zÀ-ú0-9&#93;/i", "", trim&#40;$_GET['q'&#93;&#41;&#41;;
 
  
if&#40;strlen&#40;$q&#41; >= 2 &#41; &#123;

   
$sql "SELECT m.`mes` FROM `listagem` m WHERE m.`mes` LIKE '".$q."%' ORDER BY m.`mes` DESC";
   
   
$qry mysql_query&#40;$sql&#41;;

   if&
#40;mysql_num_rows&#40;$qry&#41; > 0&#41; &#123; ?>


<select id="caixa_sugestao" name="caixa_sugestao" multiple="multiple" onchange="inserir_valor('caixa_sugestao', 'aceitar'); esconder('sugestao');" onblur="esconder('sugestao')">

<?php while&#40;$obj = mysql_fetch_object&#40;$qry&#41;&#41; &#123; $resultado = stripslashes&#40;$obj->mes&#41;; ?>

  <option value="<?=$resultado;?>"><?=$resultado;?></option>
           
<?php &#125; ?>

</select>

<?php &#125; &#125; &#125; ?>

Portanto, devem configurar com os vossos dados MySQL onde está indicado.

Em baixo seguem-se os restantes ficheiros
 
:arrow: estilo.css - A folha de estilo CSS
Código: [Seleccione]
/**
* @author =IceBurn= (www.jrfreelancer.com)
* @copyright 2007
*/
body { color: #D2D2D2; background-color: #3C3C3C; font-family: sans-serif, serif, verdana; font-size: 12px; }
h1 { margin-top: 100px; color: #FFAA00; text-align: center; }
p { text-align: center; font-family: monospace; }
a { color: #FFD400; text-decoration: none; }
a:hover { text-decoration: underline; }
input { border: 1px solid #969696; background-color: #FFD400; }
div#conteudo { width: 300px; margin: 15px auto 0 auto; }
select#caixa_sugestao {
    border: 1px solid #969696;  
width: 100%;
background-color: #F9F9F9;
height: 200px;
position: absolute;
}
input#aceitar { width: 100%; background-color: #F9F9F9; }
div#sugestao { margin: 0; padding: 0; position: absolute /* Bug do IE */; width: 302px; }


 :arrow: index.html - A página que vamos aceder para efectuar a nossa pesquisa
Código: [Seleccione]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
  <title>Ajax Auto-Sugestão | Tutorial por =IceBurn= | www.jrfreelancer.com</title>
  <meta http-equiv="content-type" content="text/html; charset=iso-8859-1"/>
  <meta name="copyright" content="=Iceburn= (c) www.jrfreelancer.com"/>
  <meta name="author" content="=IceBurn="/>
  <style type="text/css" media="all">@import "./estilo.css";</style>
  <script type="text/javascript" src="./funcoes.js"></script>
 </head>
<body>
   
 <h1>Ajax Auto-Sugestão</h1>

  <div id="conteudo">
   
   <form action="" method="post">
   
   <div>

   <label for="aceitar">Mês <small>(Ex: Maio):</small> </label> <br />
   <input id="aceitar" value="" onfocus="mostrar('sugestao')" name="mes_submetido" onkeyup="ajax_carregar('sugerir.php?q='+this.value, 'sugestao');"/>

   <div id="sugestao"></div>
   
  </div>
 
   <p><input type="submit" value="Submeter"/></p>
 
   </form>

  </div>
 
 <p>Tutorial por =IceBurn= <a href="http://jrfreelancer.com">www.jrfreelancer.com</a> &copy; 2007</p>
 
 </body>  
</html>


 :arrow: funcoes.js - O ficheiro JavaScript que alem de outras, inclui tambem uma função muito identica aquela que já tinha 'postado' no meu anterior tutorial de AJAX.
Código: [Seleccione]
<!--
/**
* @author =IceBurn= (www.jrfreelancer.com)
* @copyright 2007
*/
function ajax_carregar(carregarpagina, carregardivid) {

 try {
   obj = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
 }  
 
 catch (e) {
  alert("Erro: Não foi possivel carregar a página");
 }
 
  if(obj) {
   
obj.onreadystatechange = function(){
   
if ((obj.readyState == 4) && (obj.status == 200)) {

  document.getElementById(carregardivid).innerHTML = obj.responseText;
   
  delete obj;
  obj = null;  
}
 
 }
 
 obj.open("GET", carregarpagina, true);
 obj.send(null);
 }
 return false;
}
 
 
function esconder(id){
  if (document.getElementById){
   obj = document.getElementById(id);
 
     obj.style.display = "none";
   
  }
}

function mostrar(id){
  if (document.getElementById){
   obj = document.getElementById(id);
 
     obj.style.display = "";
   
  }
}

 
function inserir_valor(selectobjID, loadarea) {
   
  var selectobj = document.getElementById ? document.getElementById(selectobjID) : "";
  var loadarea  = document.getElementById ? document.getElementById(loadarea) : "";
 
  if (selectobj != "" && selectobj.options[selectobj.selectedIndex].value != "") {
 
      loadarea.value = selectobj.options[selectobj.selectedIndex].value;

  }
}
//-->


E pronto, temos a nossa pesquisa com auto-sugestão. :)
Para quem não quer estar a fazer copy & paste, podem fazer o download do arquivo .rar com todos os ficheiros necessários directamente do meu site, aqui está  :arrow:  http://jrfreelancer.com/tutoriais/ajax_auto_sugerir.rar

Demo disponivel aqui  :arrow: http://jrfreelancer.com/tutoriais/demos/ajax_auto_sugestao/index.html

Espero que gostem e qualquer dúvida é só dizerem.
Offline

Spread 
Membro
Mensagens 1433 Gostos 2
Troféus totais: 29
Trófeus: (Ver todos)
Super Combination Combination Topic Starter 10 Poll Votes Poll Voter Poll Starter Level 5 Level 4 Level 3 Level 2

Optimo tutorial. Parabéns ;)

Cumps 8)
Offline

OFFICER 
Membro
Mensagens 2076 Gostos 0
Troféus totais: 29
Trófeus: (Ver todos)
Super Combination Combination Topic Starter 10 Poll Votes Poll Voter Poll Starter Level 5 Level 4 Level 3 Level 2

=IceBurn=, continua o teu bom trabalho.

Obrigado por mais um grande tutorial!
Offline

asturmas 
Administrador
Mensagens 19734 Gostos 50
Feedback +2

Troféus totais: 39
Trófeus: (Ver todos)
Mobile User Windows User Super Combination Combination Topic Starter 100 Poll Votes 50 Poll Votes 10 Poll Votes Poll Voter Poll Starter

Se todos os programadores fizessem isto..
Offline

-RJ- 
Membro
Mensagens 1188 Gostos 0
Troféus totais: 30
Trófeus: (Ver todos)
Apple User Super Combination Combination Topic Starter 50 Poll Votes 10 Poll Votes Poll Voter Level 5 Level 4 Level 3

Óptimo tutorial como sempre =IceBurn=, tens feito grandes trabalhas aqui para o pessoal do +t!

Continua e parabéns!  =D&gt;
Offline

frsantos 
Membro
Mensagens 1458 Gostos 0
Troféus totais: 35
Trófeus: (Ver todos)
Linux User Mobile User Apple User Level 6 Super Combination Combination Topic Starter 10 Poll Votes Poll Voter Poll Starter

parabens, muito bom :wink:
Offline

=IceBurn= 
Membro
Mensagens 897 Gostos 3
Feedback +3

Troféus totais: 32
Trófeus: (Ver todos)
Windows User Level 6 Linux User Mobile User Super Combination Combination Topic Starter Poll Voter Poll Starter Level 5

Agrada-me saber que gostaram :)
É um prazer partilhar algo com esta comunidade, sempre o fiz e pretendo continuar a fazer, conforme vou tendo disponibilidade e novas ideias para tal.