PDA

View Full Version : Form di login con Ajax


stefano861
06-02-2014, 17:38
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

<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>


public/index.php

<?php
include_once '../Controller/LoginController.php';

$controller = new LoginController();
$view = $controller->invoke();
$view->render();


public/indexSignup.php

<?php
include_once '../Controller/SignupController.php';

$controller = new SignupController();
$view = $controller->invoke();
$view->render();


Controller/LoginController.php

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;
}

}


Controller/SignupController.php

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;
}
}


Poi nel file .js ho sempre i vari controlli. Quindi controllo sia lato server che lato client.

Come aggiungo il codice per Ajax, non ho capito...
:(

Tuvok-LuR-
06-02-2014, 18:14
se hai jQuery:
$('#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;
});

ma ha senso fare un login via ajax? dovrai comunque reindirizzare l'utente da qualche parte no? o refreshare la pagina per avere il contenuto che vedrebbe un utente loggato

stefano861
06-02-2014, 18:47
se hai jQuery:
$('#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;
});

ma ha senso fare un login via ajax? dovrai comunque reindirizzare l'utente da qualche parte no? o refreshare la pagina per avere il contenuto che vedrebbe un utente loggato
Si forse meglio la registrazione.
Ho provato a fare così ma non fa nulla.

Nel file .js:

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;
}
}


View/LoginSignup.php

<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>


Controller/SignupController.php

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;
}
}

stefano861
07-02-2014, 09:45
Qualcuno ha idee?

stefano861
07-02-2014, 18:41
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

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;
}
}


PHP

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;
}

jeremy.83
08-02-2014, 10:53
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

se hai jQuery:
$('#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;
});




ma ha senso fare un login via ajax? dovrai comunque reindirizzare l'utente da qualche parte no? o refreshare la pagina per avere il contenuto che vedrebbe un utente loggato

Sì, ha senso, ad esempio potrebbe sorgere la necessità di non caricare nulla nel caso in cui il tentativo fallisca. Ha inoltre senso anche nel caso in cui l'intero caricamento delle pagine del sito sia in ajax, anche se io lo eviterei