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:
index.html estilo.css funcoes.js sugerir.phpPara 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:
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
sugerir.php <?php
/**
* @author =IceBurn= (www.jrfreelancer.com)
* @copyright 2007
*/
/* -- -- -- CONFIGURAÇÕES - -- -- -- */
define("_DB_USER_", "user"); //-> Username MySQL
define("_DB_PASS_", "123456"); //-> Password MySQL
define("_DB_HOST_", "localhost"); //-> Host MySQL
define("_DB_NAME_", "listagem"); //-> Nome da BD
/* -- -- FIM DAS CONFIGURAÇÕES -- -- */
$link = @mysql_connect(_DB_HOST_, _DB_USER_, _DB_PASS_) or die("Ligação à Base de Dados Recusada.");
@mysql_select_db(_DB_NAME_, $link) or die("Não foi possivel seleccionar a Base de Dados.");
header("content-type: text/html; charset=iso-8859-1");
if(isset($_GET['q'])) {
$q = preg_replace("/[^a-zÀ-ú0-9]/i", "", trim($_GET['q']));
if(strlen($q) >= 2 ) {
$sql = "SELECT m.`mes` FROM `listagem` m WHERE m.`mes` LIKE '".$q."%' ORDER BY m.`mes` DESC";
$qry = mysql_query($sql);
if(mysql_num_rows($qry) > 0) { ?>
<select id="caixa_sugestao" name="caixa_sugestao" multiple="multiple" onchange="inserir_valor('caixa_sugestao', 'aceitar'); esconder('sugestao');" onblur="esconder('sugestao')">
<?php while($obj = mysql_fetch_object($qry)) { $resultado = stripslashes($obj->mes); ?>
<option value="<?=$resultado;?>"><?=$resultado;?></option>
<?php } ?>
</select>
<?php } } } ?>
Portanto, devem configurar com os vossos dados MySQL onde está indicado.
Em baixo seguem-se os restantes ficheiros
estilo.css - A folha de estilo CSS
/**
* @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; }
index.html - A página que vamos aceder para efectuar a nossa pesquisa
<!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> © 2007</p>
</body>
</html>
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.
<!--
/**
* @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á
http://jrfreelancer.com/tutoriais/ajax_auto_sugerir.rarDemo disponivel aqui
http://jrfreelancer.com/tutoriais/demos/ajax_auto_sugestao/index.htmlEspero que gostem e qualquer dúvida é só dizerem.