Usamos cookies para medir audiência e melhorar sua experiência. Você pode aceitar ou recusar a qualquer momento. Veja sobre o iMasters.
Olá http://forum.imasters.com.br/public/style_emoticons/default/blush.gif , estou aprendendo AJAX e pretendi criar uma "validação de usuário básica" e estou tendo um probleminha. Vamos deixa eu explicar: Quero que o cliente veja se há algum usuário no banco de dados com o nome da tentativa ( form ), mas sempre recebo a resposta de já há alguma pessoa registrada com tal nome.
ps: Sempre o resultado do responseText vem vazio, e já inseri o usuário no BD também.
ps2: Hoje é meu aniversário :rolleyes:
Salve salve http://forum.imasters.com.br/public/style_emoticons/default/clap.gif , obrigado pessoal.
Código AJAX:
function verLOGIN(dados) {
var ajax = openAjax();
ajax.open('POST', 'logcheck.php?', true);
ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
dataPOST = 'nick=' + dados;
ajax.send(dataPOST);
alert(ajax.responseText +'\n'+ ajax.responseText.length +'\n'+ dataPOST)
if(ajax.responseText) {
aunt = 1;
}else{
aunt = 0;
}
return false;
}Código PHP:
a<?php
header('Content-Type: text/html; charset=iso-8859-1');
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
//---------------------------------------
$datab = mysql_connect ('127.0.0.1', 'root', '1234');
mysql_select_db('user');function anti_injection($anti) {
$anti = get_magic_quotes_gpc() == 0 ? addslashes($$anti) : $anti;
$anti = preg_replace(sql_regcase("/(from|select|insert|delete|where|drop table|show tables|#|\*|--|\\\\)/"),"",$anti);
$anti = strip_tags($anti);
$anti = htmlentities($anti);
return $anti;
}
$login = anti_injection($_POST['nick']);$query = mysql_query("SELECT `user` FROM `login` WHERE user = '$login'");
$checkuser = mysql_num_rows($query);
if($checkuser == 0) {
echo "OK";
}
mysql_close($datab);
?>klaygomes muito obrigado pela ajuda.
Ainda não entendi perfeitamente o responseText, ele pega a resposta da url que mandei pelo send?
Mas então tirando o erro apresentado por você, o arquivo do AJAX está sem erros aparentes?
Muito obrigado http://forum.imasters.com.br/public/style_emoticons/default/joia.gif pelos parabéns e pela ajuda.
EDIT:
Tentando e tentando modifiquei o código para:
function openAjax() {
var ajax;
try {
ajax = new XMLHttpRequest();
} catch(ee) {
try {
ajax = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
ajax = new ActiveXObject("Microsoft.XMLHTTP");
} catch(E) {
ajax = false;
}
}
}
return ajax;
}
function verLOGIN(dados) {
var ajax = openAjax();
ajax.open('POST', 'logcheck.php', true);
ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
dataPOST = 'nick=' + encodeURIComponent(dados);
ajax.send(dataPOST);
ajax.onreadystatechange = function() {
if(ajax.readyState == 4) {
document.getElementById("carr").innerHTML = "Carregado.";
}
}
alert(ajax.responseText +'\n'+ ajax.responseText.length +'\n'+ dataPOST)
if(ajax.responseText.length = 2) {
aunt = 1;
}else{
aunt = 0;
}
return false;
}
Código php:
<?php
header('Content-Type: text/html; charset=iso-8859-1');
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
function anti_injection($anti) {
$anti = get_magic_quotes_gpc() == 0 ? addslashes($$anti) : $anti;
$anti = preg_replace(sql_regcase("/(from|select|insert|delete|where|drop table|show tables|#|\*|--|\\\\)/"),"",$anti);
$anti = strip_tags($anti);
$anti = htmlentities($anti);
return $anti;
}
$datab = mysql_connect ('127.0.0.1', 'root', '1234');
mysql_select_db('user');
//---------------------------------------
$login = anti_injection($_POST['nick']);
if(strlen($login) > 0) {
//---------------------------------------
//---------------------------------------
$query = mysql_query("SELECT `user` FROM `login` WHERE `user` = '$login'");
$checkuser = mysql_num_rows($query);
if($checkuser == FALSE) {
echo "<b>OK</b>\n";
} else {
echo "<b>FAIL</b>\n";
}
mysql_close($datab);
} else {
echo "LIMPO";
}
?>
Edit 2:
Tentei agora no IE ele reporta um erro:
Erro 221:Os dados necessários pra concluir a operação ainda não estão disponíveis.
Corrigido, coloquei o responseText dentro do
ajax.onreadystatechange = function() e deu certo.
Em primeiro lugar, feliz aniversário!
Vamos lá.
Altere este linha:
(...)
(...)
para:
(..)
(..)
Porque? Se o usuário possuir caracteres especiais o post não seria enviado da forma antiga.
O problema de dar falso negativo, você terá que verificar no seu PHP, desculpa não sei programar nesta linguagem não poderei ajudar.
Mas uma dica, tenta depurar os valores que estão recebidos (que tal incluir depois do echo ok um echo informando o nome da variável e o sql que foi processado?)
Abraços,