Ajax login form
Posted by thietkewebsitegiare trên 18/06/2009
Bài này hướng dẫn các bạn viết 1 form login bằng Ajax. Mục tiêu không nhằm giới thiệu 1 ajax framework nào mà viết toàn bộ từ bước cơ bản nhất kỹ thuật Ajax để có thể hiểu sâu Ajax là gì.
1. Tạo form login
Code:
<body>
<!– Include AJAX Framework –>
<script src=”ajax/ajax_framework.js” language=”javascript”></script>
<!– Show Message for AJAX response –>
<div id=”login_response”></div>
<div id=”divForm”>
<!– Form: the action=”javascript:login()”call the javascript function “login” into ajax_framework.js –>
<form action=”javascript:login()” method=”post”>
<input name=”email” type=”text” id=”emailLogin” value=””/>
<input name=”psw” type=”password” id=”pswLogin” value=””/>
<input type=”submit” name=”Submit” value=”Login”/>
</form>
</div>
</body>
Để ý thấy khi submit, ta dùng một JS function để khởi tạo lời gọi Ajax: login(). Bạn không tìm thấy đoạn JS cho login() ở đây vì tôi link với 1 file .js bên ngoài tên là ajax-framework.js.
2. Tạo file .js để viết code Ajax
Code:
/* —————————- */
/* XMLHTTPRequest Enable */
/* —————————- */
function createObject() {
var request_type;
var browser = navigator.appName;
if(browser == “Microsoft Internet Explorer”){
request_type = new ActiveXObject(“Microsoft.XMLHTTP”);
}else{
request_type = new XMLHttpRequest();
}
return request_type;
}
var http = createObject();
/* ————————– */
/* LOGIN */
/* ————————– */
/* Required: var nocache is a random number to add to request. This value solve an Internet Explorer cache issue */
var nocache = 0;
function login() {
// Optional: Show a waiting message in the layer with ID ajax_response
document.getElementById(‘login_response’).innerHTML = “Loading…”
// Required: verify that all fileds is not empty. Use encodeURI() to solve some issues about character encoding.
var email = encodeURI(document.getElementById(’emailLogin’).value);
var psw = encodeURI(document.getElementById(‘pswLogin’).value);
// Set te random number to add to URL request
nocache = Math.random();
// Pass the login variables like URL variable
http.open(‘get’, ‘login.php?email=’+email+’&psw=’+psw+’&nocache = ‘+nocache);
http.onreadystatechange = loginReply;
http.send(null);
}
function loginReply() {
if(http.readyState == 4){
var response = http.responseText;
alert(response);
if(response == ‘0’){
// if login fails
document.getElementById(‘login_response’).innerHTML = ‘Login failed! Verify user and password’;
// else if login is ok show a message: “Welcome + the user name”.
} else {
document.getElementById(‘login_response’).innerHTML = ‘Welcome ‘+response;
document.getElementById(‘divForm’).style.display = ‘none’;
}
}
}
Tập trung vào hàm login(), công việc của chúng ta là lấy được dữ liệu nhậu của user thông qua JS, dùng document.getElementById() để tìm đúng textbox cần lấy giá trị.
Sau đó, ta tạo một chuỗi query string, có thêm một giá trị nocache là giá trị phát sinh random nhằm chống lại việc trình duyệt cache file login.php, không truyền về server.
Đối tượng http là một đối tượng XMLHTTPRequest, giúp ta gửi 1 request tới server, đối tượng này tạo ra bởi hàm CreateObject().
Đoạn lệnh mock up này giúp chúng ta biết khi nào nhận được kết quả từ server thì sẽ gọi tiếp hàm loginReply() để xử lý.
http.onreadystatechange = loginReply;
Sau khi đã đặt thông tin hàm xử lý (gọi là hàm CallBack) thì http.send() sẽ gửi thông tin cần xử lý tới server. Ở đây, chúng ta gửi tới 1 file chuyên xử lý lời gọi Ajax là login.php
3. Tạo file xử lý lời gọi Ajax
File login.php
Code:
<?php
if(isset($_GET[’email’]) && isset($_GET[‘psw’])){
$email = $_GET[’email’];
$psw = $_GET[‘psw’];
if ($email==’hung5s@yahoo.com’ && $psw == ‘123’)
echo $email;
else
echo ‘0’;
}
?>
Bạn thấy rằng việc xử lý này cốt trả về một giá trị (hãy coi nó như 1 hàm trả về giá trị) nên ta chỉ trả về giá trị qua lệnh echo và giá trị đó phải dễ xử lý như là 0 hay $email.
Tiếp theo, function loginReply() xử lý giá trị trả về để hiển thị kết quả.
Bài viết chỉ tới đây để đơn giản cho các bạn thử nghiệm. Reply tiếp theo sẽ phân tích sâu hơn bản chất của Ajax và về đối tượng XMLHttpRequest.
Chúc bạn thành công – www.ticsoft.com (Nguồn: phpvn)
Bình luận về bài viết này