Menu
- 14. A web application for implementation: The user is first served a login page which takes user's name and password. After Submitting the details the server checks these values against the data from a database and takes the following decisions.
- • If name and password matches, serves a welcome page with user's full name.
- • If name matches and password doesn't match, then serves “password mismatch” page
- • If name is not found in the database, serves a registration page, where user’s full name is asked and on submitting the full name, it stores, the login name, password and full name in the database (hint: use session for storing the submitted login name and password)
Aim: Modify the above program to use AJAX to show the result on the same page below the submit button
index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Login</title>
</head>
<body>
<form id="loginForm">
<input type="text" placeholder="Name" id="name" required>
<input type="password" placeholder="Password" id="pwd" required>
<button type="submit">Submit</button>
</form>
<div id="result"></div>
<script>
var xhttp = new XMLHttpRequest();
var loginForm = document.getElementById('loginForm');
loginForm.addEventListener("submit", submit, false);
function submit(e) {
e.preventDefault();
var username = document.getElementById('name').value;
var userpwd = document.getElementById('pwd').value;
var result = document.getElementById("result");
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var xmlDoc = xhttp.responseXML;
var name = xmlDoc.getElementsByTagName("name")[0].childNodes[0].nodeValue;
var pwd = xmlDoc.getElementsByTagName("pwd")[0].childNodes[0].nodeValue;
console.log(name + pwd);
if (name == username && pwd == userpwd) {
result.innerHTML = '<h1>Successfully logged in</h1>';
} else {
result.innerHTML = '<h1>Wrong Details</h1>';
}
loginForm.reset();
}
};
xhttp.open("GET", "users.xml", true);
xhttp.send();
}
</script>
</body>
</html>
login.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Login</title>
</head>
<body>
<h1>Successfully logged in</h1>
</body>
</html>
users.xml
<?xml version="1.0" encoding="utf-8"?>
<users>
<name>kumar</name>
<pwd>admin</pwd>
</users>