Validando login com Ajax
Criei este sistema que valida se o usuário esta cadastrado antes mesmo de acabar de concluir o cadastro.
Se tentarem se cadastrar com um nome de usuário que já existe aparecerá uma mensagem quando o campo nome perder o foco.
O sistema é muito simples e não tem segredo e eu não fiquei perdendo tempo enfeitando o código com CSS nem nada, o foco aqui é o AJAX e mostrar que ele retorna true ou false depois de digitar o nome de usuário.
Arquivo cadastro.html:
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1257" />
<title>Login</title>
<style>
<!--
html, body {
margin:0;
padding:0;
}
fieldset {
width:260px;
margin:0 auto;
padding:30px;
}
.texto {
width:250px;
border:1px solid gray;
}
.erro {
width:250px;
border:1px solid red;
}
.alerta2 {
border:1px solid gray;
}
-->
</style>
<script src="ajax.js" type="text/javascript"></script>
<script src="funcoes.js" type="text/javascript"></script>
</head>
<body>
<fieldset>
<legend>Usuario</legend>
<form id="form1" name="form1" method="post" action="login.php">
<div id="alerta"></div>
<label>Login</label><br />
<input name="login" id="login" type="text" maxlength="30" class="texto" onblur="javascript: envia('receber.php', 'POST', false);" /><br />
<labeL>Senha</labeL><br />
<input name="senha" id="senha" type="password" maxlength="30" class="texto" /><br />
<input name="botao" type="submit" value="Enviar" />
</form>
</fieldset>
</body>
</html>
Arquivo ajax.js:
function ajax() {
};
ajax.prototype.iniciar = function() {
try{
this.xmlhttp = new XMLHttpRequest();
}catch(ee){
try{
this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(E){
this.xmlhttp = false;
}
}
}
return true;
}
ajax.prototype.ocupado = function() {
estadoAtual = this.xmlhttp.readyState;
return (estadoAtual && (estadoAtual < 4));
}
ajax.prototype.processa = function() {
if (this.xmlhttp.readyState == 4 && this.xmlhttp.status == 200) {
return true;
}
}
ajax.prototype.enviar = function(url, metodo, modo) {
if (!this.xmlhttp) {
this.iniciar();
}
if (!this.ocupado()) {
if(metodo == "GET") {
this.xmlhttp.open("GET", url, modo);
this.xmlhttp.send(null);
} else {
this.xmlhttp.open("POST", url, modo);
this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
this.xmlhttp.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
this.xmlhttp.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
this.xmlhttp.setRequestHeader("Pragma", "no-cache");
this.xmlhttp.send(url);
}
if (this.processa) {
return unescape(this.xmlhttp.responseText.replace(/\+/g," "));
}
}
return false;
}
Arquivo funcoes.js:
function envia(url, metodo, modo)
{
var login = document.getElementById('form1').login.value;
remoto = new ajax();
xmlhttp = remoto.enviar(url + "?login=" + login, metodo, modo );
if(xmlhttp) {
document.getElementById('login').className = 'erro';
document.getElementById('alerta').className = 'alerta2';
document.getElementById("alerta").innerHTML = 'Esse usuario ja esta cadastrado';
} else {
document.getElementById('login').className = 'texto';
document.getElementById('alerta').className = '';
document.getElementById("alerta").innerHTML = '';
}
}
Arquivo receber.php:
<?php
$texto = $_REQUEST["login"];
// no lugar do if basta fazer uma conexao com o banco e um select pesquisando o nome do usuario se ja existe
//acho que todos sabem fazer isso ne?
if($texto == "Fulano") {
echo true;
} else {
echo false;
}
Tá ai só com o funcional para vocês adaptarem do jeito que achar melhor! ?>
muito bom seu blog, ja esta nos favoritos