|
|
|
![]() |
|
Strumenti |
![]() |
#1 |
Member
Iscritto dal: Nov 2013
Messaggi: 62
|
Form di login con Ajax
Ciao a tutti, attualmente ho una pagina .php (la View) (che contiene principalmente codice html) che contiene un form per il login e un form per la registrazione.
Nell'action del form richiamo un file .php (il file pubblico) che crea una istanza di un controller specifico per gestire gli input dei due form. Questo controller prende i dati inseriti dall'utente, li elabora, controlla che i dati siano corretti ed esegue una insert (caso registrazione) o una select (caso login). Se ci sono errori passa tali stringhe di errori alla vista che li stamperà a video. Quello che vorrei fare ora è usare Ajax (mai usato prima, e per ora, leggendo un pò su Internet, non c'ho capito quasi nulla) per rendere questi form migliori, cioè vorrei che il controllo dei dati e il loro risultato (dati corretti o meno) fosse fatto da Ajax, in modo asincrono. Non so come iniziare.. Mi aiutate? Quello che ho ora è: View/LoginSignup.php Codice:
<form action="../public/index.php" method="post" id="modLogin_form" onSubmit="checkLogin()"> Username: <input type="text" name="login_username" id="lu"/> Password: <input type="password" name="login_password" id="lp"/> <input type="submit" value="Login" name="login-submit" onClick="checkLogin()"/> </form> <form action="../public/indexSignup.php" id="modSignup_form" method="post" onSubmit="checkSignup()"> Username: <input type="text" name="reg_username" id="ru"/> Password: <input type="password" name="reg_password" id="rp" /> E-mail: <input type="text" name="reg_email" id="re" /> <input type="submit" value="Sign up" name="reg-submit" onClick="checkSignup()"/> </form> Codice:
<?php include_once '../Controller/LoginController.php'; $controller = new LoginController(); $view = $controller->invoke(); $view->render(); Codice:
<?php include_once '../Controller/SignupController.php'; $controller = new SignupController(); $view = $controller->invoke(); $view->render(); Codice:
class LoginController { public $user; public $userRepository; public $view; //Crea un array per gli errori public $errorsL; public function __construct() { $this->userRepository = new UserRepository(); $this->errorsL = array(); $this->view = new View('LoginSignup'); $db = Database::getInstance(); } public function checkData($username, $password) { preg_match("/[\|\(\)<>%\*+={}@#']|(=)+(!)|[-]{2}/", $username, $arrayU); preg_match("/[\|\(\)<>%\*+={}@#']|(=)+(!)|[-]{2}/", $password, $arrayP); if($arrayU) { $this->errorsL['login-incorrectUsername'] = "Incorrect username."; $this->view->setData('errorsL', $this->errorsL); return false; } else if($arrayP) { $this->errorsL['login-incorrectPassword'] = "Incorrect password."; $this->view->setData('errorsL', $this->errorsL); return false; } else if($username === "" || $password === "") { $this->errorsL['login-empty'] = "Some field are empty, please try again."; $this->view->setData('errorsL', $this->errorsL); return false; } else { $this->user = $this->userRepository->findByUsername($username); if($this->user != NULL) { if($this->user->getPassword() === $password) { return true; } else { $this->errorsL['login-incorrectPassword'] = "Incorrect password."; $this->view->setData('errorsL', $this->errorsL); return false; } } else { $this->errorsL['login-unregisteredUser'] = "There is no user with this username."; $this->view->setData('errorsL', $this->errorsL); return false; } } } public function checkLogin() { if(isset($_POST['login-submit'])) { if(isset($_POST['login_username']) && isset($_POST['login_password'])) { $username = $_POST['login_username']; $password1 = $_POST['login_password']; $password = addslashes($password1); if($this->checkData($username, $password)) { $_SESSION['logged_in'] = 1; $_SESSION['username'] = $username; header("Location: ../public/home.php", true, 302); } } else { $this->errorsL['login-empty'] = "Some fields are empty."; $this->view->setData('errorsL', $this->errorsL); } } else { return; } } public function invoke() { $this->checkLogin(); return $this->view; } } Codice:
class SignupController { public $user; public $userRepository; //Crea un array per gli errori e uno per i successi public $errorsR; public $successesR; public $view; public function __construct() { $this->userRepository = new UserRepository(); $this->errorsR = array(); $this->successesR = array(); $this->view = new View('LoginSignup'); $db = Database::getInstance(); } public function checkData($username, $password, $email) { //code.. } public function checkUsername($username) { //code.. } public function checkPassword($password) { //code.. } public function checkEmail($email) { //code.. } public function checkSignup() { if(isset($_POST['reg-submit'])) { if(isset($_POST['reg_username']) && isset($_POST['reg_password']) && isset($_POST['reg_email'])) { $username = $_POST['reg_username']; $password1 = $_POST['reg_password']; $email = $_POST['reg_email']; $password = addslashes($password1); if($this->checkData($username, $password, $email)) { $db = Database::getInstance(); $this->user = new User(); $this->user->setUsername($username); $this->user->setEmail($email); $this->user->setPassword($password); $this->user->save(); $this->successesR['reg-completed'] = "Registration completed successfully."; $this->view->setData('successesR', $this->successesR); } } else { $this->errorsR['empty-field'] = "Some fields are incorrect."; $this->view->setData('errorsR', $this->errorsR); } } else { return; } } public function invoke() { $this->checkSignup(); return $this->view; } } Come aggiungo il codice per Ajax, non ho capito... ![]() Ultima modifica di stefano861 : 06-02-2014 alle 17:43. |
![]() |
![]() |
![]() |
#2 |
Senior Member
Iscritto dal: Sep 2001
Città: Pisa
Messaggi: 2212
|
se hai jQuery:
Codice:
$('#modLogin_form, #modSignup_form').on('submit', function () { $.post( $(this).attr('action'), $(this).serialize() ).done(function (response) { alert(response); }).fail(function (error) { alert('Errore: '+error); }); return false; });
__________________
7800X3D | 32GB DDR5 6400C30@TUNED | RTX 4090 | LG 32GQ950-B | Fractal Torrent | bequiet! Dark Power Pro 11 850w | Iliad Fibra 5Gb Ultima modifica di Tuvok-LuR- : 06-02-2014 alle 17:29. |
![]() |
![]() |
![]() |
#3 | |
Member
Iscritto dal: Nov 2013
Messaggi: 62
|
Quote:
Ho provato a fare così ma non fa nulla. Nel file .js: Codice:
function setXMLHttpRequest() { var xhr = null; if(window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } else if(window.ActiveXObject) { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } return xhr; } var xhrObj = setXMLHttpRequest(); function checkUsr(usr) { var url = "../indexSignup.php?checkusr=" + usr; xhrObj.open("GET", url, true); xhrObj.onreadystatechange = updateUsr; xhrObj.send(null); } function updateUsr() { if(xhrObj.readyState === 4) { var risp = xhrObj.responseText; document.getElementById("reg_username").innerHTML = risp; } } Codice:
<form action="../public/index.php" method="post" id="modLogin_form" onSubmit="checkLogin()"> Username: <input type="text" name="login_username" id="lu"/> Password: <input type="password" name="login_password" id="lp"/> <input type="submit" value="Login" name="login-submit" onClick="checkLogin()"/> </form> <?php if(isset($ajax)) { if(count($ajax) > 0) { print_r($ajax); } } ?> <form action="../public/indexSignup.php" id="modSignup_form" method="post" onSubmit="checkSignup()"> Username: <input type="text" name="reg_username" id="ru" onChange="checkUsr(this.value);"/> Password: <input type="password" name="reg_password" id="rp" /> E-mail: <input type="text" name="reg_email" id="re" /> <input type="submit" value="Sign up" name="reg-submit" onClick="checkSignup()"/> </form> Codice:
class SignupController { public $user; public $userRepository; //Crea un array per gli errori e uno per i successi public $errorsR; public $successesR; public $view; public $ajax; public function __construct() { $this->userRepository = new UserRepository(); $this->errorsR = array(); $this->successesR = array(); $this->ajax = array(); $this->view = new View('LoginSignup'); $db = Database::getInstance(); } public function checkData($username, $password, $email) { //code.. } public function checkUsername($username) { //code.. } public function checkPassword($password) { //code.. } public function checkEmail($email) { //code.. } public function checkSignup() { if(isset($_POST['reg-submit'])) { if(isset($_POST['reg_username']) && isset($_POST['reg_password']) && isset($_POST['reg_email'])) { $username = $_POST['reg_username']; $password1 = $_POST['reg_password']; $email = $_POST['reg_email']; $password = addslashes($password1); if($this->checkData($username, $password, $email)) { $db = Database::getInstance(); $this->user = new User(); $this->user->setUsername($username); $this->user->setEmail($email); $this->user->setPassword($password); $this->user->save(); $this->successesR['reg-completed'] = "Registration completed successfully."; $this->view->setData('successesR', $this->successesR); } } else { $this->errorsR['empty-field'] = "Some fields are incorrect."; $this->view->setData('errorsR', $this->errorsR); } } else { return; } } public function checkAjax() { if(isset($_GET['checkusr'])){ $usr = $_GET['checkusr']; $risp = $this->model->compareUsr($usr); $this->user = $this->userRepository->findByUsername($usr); if($this->user === NULL) { $this->ajax['err'] = "Username disponibile."; $this->view->setData('ajax', $this->ajax); } else if($risp > 0) { $this->ajax['succ'] = "Username non disponibile."; $this->view->setData('ajax', $this->ajax); } } } public function invoke() { if(isset($_GET['checkusr'])) { $this->checkAjax(); } $this->checkSignup(); return $this->view; } } |
|
![]() |
![]() |
![]() |
#4 |
Member
Iscritto dal: Nov 2013
Messaggi: 62
|
Qualcuno ha idee?
|
![]() |
![]() |
![]() |
#5 |
Member
Iscritto dal: Nov 2013
Messaggi: 62
|
Ho modificato queste due parti di codice. Ora la console di Chrome mi da questo errore:
GET http://localhost/.. ./index.php?checkusr=john 404 (Not Found) javascript.js:477 checkUsr javascript.js:477 onchange index.php:82 XHR finished loading: "http://localhost/.. ./index.php?checkusr=john". javascript.js:477 checkUsrjavascript.js:477 onchange JAVASCRIPT Codice:
function setXMLHttpRequest() { var xhr = null; //Browser standard con supporto nativo (per tutti i browser tranne Explorer) if(window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } //MSIE 6 con ActiveX (per Explorer) else if(window.ActiveXObject) { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } return xhr; } var xhrObj = setXMLHttpRequest(); function checkUsr(usr) { var url = "public/index.php?checkusr=" + usr; //var url = "../indexSignup.php?checkusr=" + usr; xhrObj.open("GET", url, true); xhrObj.onreadystatechange = updateUsr; xhrObj.send(null); RIGA 477 } function updateUsr() { if(xhrObj.readyState === 4) { var risp = xhrObj.responseText; document.getElementById("reg_username").innerHTML = risp; } } Codice:
public function checkAjax() { if(isset($_GET['checkusr'])){ $usr = $_GET['checkusr']; //$risp = $this->model->compareUsr($usr); $this->user = $this->userRepository->findByUsername($usr); if($this->user === NULL) { $this->ajax['succ'] = "Username disponibile."; $this->view->setData('ajax', $this->ajax); } else if($risp > 0) { $this->ajax['err'] = "Username non disponibile."; $this->view->setData('ajax', $this->ajax); } } } public function invoke() { if(isset($_GET['checkusr'])) { $this->checkAjax(); //session_destroy(); } $this->checkLogin(); //Esegue i controlli sui dati del form di login $this->checkSignup(); return $this->view; } |
![]() |
![]() |
![]() |
#6 | |
Senior Member
Iscritto dal: May 2007
Città: DiSaronno Originale
Messaggi: 2376
|
Se vuoi andare di ajax, usa il framework JQuery o altri simili, impara ad usarli bene. Javascript da solo è molto carente e lento nello scrivere codice. Peraltro JQuery ottimizza molto l'esecuzione degli ajax dando inoltre la possibilità di usare tantissime opzioni, una su tutte ad esempio l'esecuzione sincrona/asincrona.
Io non lo farei così, tuttavia a occhio il codice che ti ha postato Tuvok-LuR che riporto mi sembra corretto Quote:
__________________
Dell XPS 9570 Powered by Arch Linux || Motorola One Vision Ho concluso con raffaelev, Iceworld, stebru, Dichy, AXIP, Quakeman e Swampo |
|
![]() |
![]() |
![]() |
Strumenti | |
|
|
Tutti gli orari sono GMT +1. Ora sono le: 15:52.