thinkbrunus Posted March 14, 2009 at 07:05 PM Report Share #250713 Posted March 14, 2009 at 07:05 PM Olá, estou a tentar implementar um código para fazer o login em AJAX&PHP, mas não estou a conseguir resultados...será que podem dar-me uma ajudinha a ver se está alguma coisa errada no meu código? index.php <input name="btnLogin" value="Login" id="btnLogin" type="submit" onclick="login()" /> ajax.js var xmlHttp; var nocache = 0; function login(){ xmlHttp = getXmlHttpObject(); //inicializa variável com identificação do browser var username = encodeURI(document.getElementById('txtUserName').value); var password = encodeURI(document.getElementById('txtPassword').value); nocache = Math.random(); xmlHttp.open("GET","login.php?username="+username+"&password="+password"&nocache="+nocache); xmlHttp.onreadystatechange = function(){ if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") { document.getElementById("iMenuV").innerHTML = xmlHttp.responseText; } } xmlHttp.send(null); } //verifica qual o browser utilizado function getXmlHttpObject(){ var xmlHttp = null; try { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); id_browser=1; } catch (e) { // Internet Explorer try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); id_broowser=2; } catch (e) { try { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); id_browser=3; } catch (e) { alert("O browser não suporta AJAX!"); return false; } } } return xmlHttp; } login.php <?php include('includes/config.php'); $username = $_GET['txtUserName']; $password = $_GET['txtPassword']; $query = "SELECT * FROM ndetalhe WHERE nome='" . $username . "' AND password='" . $password . "'"; $result = mysql_query($query) or die('Query failed: ' . mysql_error()); $validUser = mysql_num_rows($result); if ($validUser > 0){ echo "Confere!"; }else{ echo "Dados incorrectos!"; } ?> O objectivo é depois de isto funcionar, trabalhar com sessões, mas isso é outra conversa. Link to comment Share on other sites More sharing options...
skin Posted March 14, 2009 at 07:28 PM Report Share #250719 Posted March 14, 2009 at 07:28 PM O teu código tem montes de erros... Alguns deles corrigidos: <input name="btnLogin" value="Login" id="btnLogin" type="submit" onclick="javascript:login();" /> xmlHttp.open("GET", "login.php?username="+username+"&password="+password+"&nocache="+nocache); if (xmlHttp.readyState == 4) { $username = $_GET['username']; $password = $_GET['password']; Our lives begin to end the day we become silent about things that matter - Martin Luther King Link to comment Share on other sites More sharing options...
thinkbrunus Posted March 14, 2009 at 07:49 PM Author Report Share #250725 Posted March 14, 2009 at 07:49 PM Estou a ver os erros que referiste, apenas noto diferença no <login();> Link to comment Share on other sites More sharing options...
skin Posted March 14, 2009 at 07:55 PM Report Share #250726 Posted March 14, 2009 at 07:55 PM No segundo erro faltava-te um +. No terceiro erro tinhas uma condição que não era necessária. E nos outros dois tu tinhas txtUserName e txtPassword enquanto estavas a passar os parametros como username e password. Our lives begin to end the day we become silent about things that matter - Martin Luther King Link to comment Share on other sites More sharing options...
thinkbrunus Posted March 14, 2009 at 08:03 PM Author Report Share #250729 Posted March 14, 2009 at 08:03 PM Tens razão, eu é que já tou todo queimado... Link to comment Share on other sites More sharing options...
thinkbrunus Posted March 14, 2009 at 08:20 PM Author Report Share #250734 Posted March 14, 2009 at 08:20 PM só uma questão, no firefox ele não está a mostrar nada, alguma compatibilidade? Link to comment Share on other sites More sharing options...
skin Posted March 14, 2009 at 10:42 PM Report Share #250757 Posted March 14, 2009 at 10:42 PM Possivelmente... Instala o FireBug e verifica ou então coloca tudo online e envia-me o link para eu verificar. Our lives begin to end the day we become silent about things that matter - Martin Luther King Link to comment Share on other sites More sharing options...
thinkbrunus Posted March 15, 2009 at 10:42 AM Author Report Share #250792 Posted March 15, 2009 at 10:42 AM Vou instalar o FireBug e deixo também o link para dares uma vista de olhos sff. http://teste.vibeltaxis.com/ Obrigado! Link to comment Share on other sites More sharing options...
skin Posted March 15, 2009 at 11:45 AM Report Share #250794 Posted March 15, 2009 at 11:45 AM Corrige: <input name="btnLogin" value="Login" id="btnLogin" type="submit" onclick="javascript:login();" /> Depois de eu corrigir isto começou a dar bem 😉 Our lives begin to end the day we become silent about things that matter - Martin Luther King Link to comment Share on other sites More sharing options...
thinkbrunus Posted March 15, 2009 at 12:02 PM Author Report Share #250798 Posted March 15, 2009 at 12:02 PM Bom dia skin! Sinceramente já me sinto mal em colocar estas dúvidas, pois isto são erros talvez de alguma falta de prática e também de alguma atenção... Já actualizei a tag que disseste e não aparece...quer dizer aparece msg box mas sem o texto, tal como aparece no ie. obrigado pela paciência! Link to comment Share on other sites More sharing options...
thinkbrunus Posted March 15, 2009 at 05:37 PM Author Report Share #250856 Posted March 15, 2009 at 05:37 PM Está resolvido, em vez de chamar a função login no botão (onsubmit) coloquei no action do form. Agora continuo com um problema, como é que poderei fazer desaparecer o form do login quando o login for validado? Estou a tentar o seguinte: index.php <div id="iBlockUser"> <?php if (!isset($_SESSION['nome'])) { unset($_SESSION['nome']); echo"<script language='javascript' src='scripts/ajax.js'></script> <table><form id='frmLogin' name='frmLogin' method='post' action='javascript:login()' > <tr> <td>Username:</td> <td><input type='text' name='txtUserName' id='txtUserName' size='14' maxlength='14' /></td> </tr> <tr> <td>Password:</td> <td><input type='text' name='txtPassword' id='txtPassword' size='14' maxlength='14' /></td> </tr> <tr> <td colspan='2' align='right'><input name='btnLogin' value='Login' id='btnLogin' type='submit' /></td> </tr> </form> </table>"; }else{ include('seguranca.php'); } ?> E neste include quero colocar a informação do user que está logado Link to comment Share on other sites More sharing options...
skin Posted March 15, 2009 at 08:51 PM Report Share #250900 Posted March 15, 2009 at 08:51 PM Não sei porque não funcionou, eu testei em firefox como te disse e funcionou correctamente... Utiliza uma lógica deste género: se não existir sessão form de login se sessão inválida form de login se sessão correcta qualquer coisa fim se Our lives begin to end the day we become silent about things that matter - Martin Luther King Link to comment Share on other sites More sharing options...
thinkbrunus Posted March 16, 2009 at 10:53 AM Author Report Share #250941 Posted March 16, 2009 at 10:53 AM Temporariamente não consigo colocar on-line o protótipo do site para testar, estou a testar localmente e depois de autenticar os dados, surge uma janela que é gerada automaticamente e aparece o código todo da página...será por estar a testar localmente? Link to comment Share on other sites More sharing options...
skin Posted March 16, 2009 at 08:43 PM Report Share #251083 Posted March 16, 2009 at 08:43 PM Temporariamente não consigo colocar on-line o protótipo do site para testar, estou a testar localmente e depois de autenticar os dados, surge uma janela que é gerada automaticamente e aparece o código todo da página...será por estar a testar localmente? Tens o PHP activo? E estás a aceder correctamente? Our lives begin to end the day we become silent about things that matter - Martin Luther King Link to comment Share on other sites More sharing options...
thinkbrunus Posted March 16, 2009 at 09:13 PM Author Report Share #251095 Posted March 16, 2009 at 09:13 PM Penso que sim, pois antes de enviar valores em ajax, testei query's com valores definido e funcionava... Tenho o site no htdocs, e acedo assim: http://localhost/site/ Não sei se assim respondo à tua pergunta? Isto apenas acontece quando funciona em localhost, não devia acontecer pois não? Link to comment Share on other sites More sharing options...
skin Posted March 18, 2009 at 09:13 PM Report Share #251679 Posted March 18, 2009 at 09:13 PM Sim, respondeste à minha pergunta. Então não sei porque não funciona na tua máquina... Será problemas de permissões de acesso a ficheiros? Não estou a ver o que possa ser. Our lives begin to end the day we become silent about things that matter - Martin Luther King Link to comment Share on other sites More sharing options...
thinkbrunus Posted March 19, 2009 at 03:34 PM Author Report Share #251912 Posted March 19, 2009 at 03:34 PM Alô! Alterei a forma de chamar a função que faz a autenticação: <form id="frmLogin" name="frmLogin" method="post" action="javascript:login()"> Desta forma não estou a ter problemas, faz a autenticação como deve ser! Agora começa a outra guerra, estou a tentar inicializar a sessão quando a autenticação é feita. Mas ando aqui às voltas a tentar colocar no responseText... document.getElementById("iBlockUser").innerHTML = "<?php session_start(); $_SESSION['username'] = "+username+";"; Tou a chegar à conclusão que assim não funciona...a minha ideia é registar a na sessão o username e depois apresentar uma mensagem de boas vindas, chamando o nome armazenado na sessão. Link to comment Share on other sites More sharing options...
skin Posted March 20, 2009 at 07:39 PM Report Share #252155 Posted March 20, 2009 at 07:39 PM Se tens o código que mostraste em javascript dentro de um .js file ele não vai funcionar. Precisas de ter isso dentro de um .php file ou então com o javascript ir buscar isso a um .php Our lives begin to end the day we become silent about things that matter - Martin Luther King Link to comment Share on other sites More sharing options...
thinkbrunus Posted March 21, 2009 at 04:22 PM Author Report Share #252306 Posted March 21, 2009 at 04:22 PM Já fiz mudanças no código, espero que para melhor. Optei por colocar na página index.php o seguinte: [code}]<div id="iBlockUser"> <?php if (empty($_SESSION['username'])){ include('login.php'); } else { echo "<div id='iBlockUserLogout'>" . $_SESSION['username'] . "</div>"; } ?> </div>[/code] No tal código AJAX: function login(){ xmlHttp = getXmlHttpObject(); //inicializa variável com identificação do browser var username = encodeURI(document.getElementById('txtUserName').value); var password = encodeURI(document.getElementById('txtPassword').value); nocache = Math.random(); xmlHttp.open("GET", "loginResponse.php?username="+username+"&password="+password+"&nocache="+nocache); xmlHttp.onreadystatechange = function(){ if (xmlHttp.readyState == 4) { if (xmlHttp.responseText == 0){ alert('Dados incorrectos!'); } else{ document.getElementById("iBlockUser").innerHTML = xmlHttp.responseText; } } } xmlHttp.send(null); } E na página .php que retorna se a autenticação é verdadeira: <?php session_start(); include('includes/settings.php'); //CÓDIGO LOGIN AJAX&PHP $username = $_GET['username']; $password = $_GET['password']; $sql = "SELECT * FROM ndetalhe WHERE nome='" . $username . "' AND password='" . $password . "'"; $query = mysql_query($sql) or die('Query failed: ' . mysql_error()); $result = mysql_num_rows($query); if ($result > 0){ $_SESSION['username'] = $result -> nome; }else{ echo "0"; } ?> Agora estou com outro problema (parece que não tem fim!), quando vou para outra página no site ele não me vai buscar o ficheiro o endereço que tenho no código AJAX xmlHttp.open("GET", "loginResponse.php?username="+username+"&password="+password+"&nocache="+nocache); Isto porque estou a "arquitectar" o site por secções, ou seja se entrar noutra secção ele já não me vai buscar o ficheiro como é normal...é necessário alterar o caminho: xmlHttp.open("GET", "../loginResponse.php?username="+username+"&password="+password+"&nocache="+nocache); Depois de tanta luta, agora tenho aqui um belo galo! Link to comment Share on other sites More sharing options...
skin Posted March 22, 2009 at 01:25 PM Report Share #252477 Posted March 22, 2009 at 01:25 PM Cria mais do que um ficheiro e alteras só o path... É a solução mais simples. Our lives begin to end the day we become silent about things that matter - Martin Luther King Link to comment Share on other sites More sharing options...
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now