Web Science/Part1: Foundations of the web/Dynamic Web Content/Ajax and the XMLHttpRequest class
Appearance
Ajax and the XMLHttpRequest class
- be aware of JavaScript APIs
- know some of the standard JavaScript libraries
- be able to understand the concept of Ajax requests.
index.html
<html>
<head><title>Registration Form</title></head>
<body>
<script>
function validator(){
var name = document.getElementById("userinput").value;
if( name.length<3){
document.getElementById("warning").innerHTML = "User name is too short. Please enter at least 3 characters.";
}
else {
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
var ajax = new XMLHttpRequest();
}
else { // code for IE6, IE5
var ajax = new ActiveXObject("Microsoft.XMLHTTP");
}
ajax.open('GET', 'servlet?name='+name, true);
ajax.onreadystatechange = function(){
if (ajax.readyState == 4 && ajax.status == 200){
document.getElementById("warning").innerHTML = ajax.responseText;
}
};
ajax.send();
}
}
</script>
<h1>Registration Form for the Web Science MOOC</h1>
<form action="servlet" method="POST">
<label for="userinput">Enter User:</label>
<input name="username" id="userinput" type ="text" onchange="validator()"/><span id="warning" style="color:red"></span>
<br>
<label for="emailinput">Enter email</label>
<input name="email" id="emailinput" type ="text" />
<br>
<input name="submit" id="submitbutton" type="submit" value="register"/>
</form>
</body>
</html>
Register.java
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;
public class Register extends HttpServlet {
private Connection connect = null;
private Statement statement = null;
private ResultSet resultSet = null;
public Register() {
try {
Class.forName("com.mysql.jdbc.Driver");
// Setup the connection with the DB
connect = DriverManager
.getConnection("jdbc:mysql://localhost/mooc?"
+ "user=mooc&password=studywebscience");
// Statements allow to issue SQL queries to the database
statement = connect.createStatement();
// Result set get the result of the SQL query
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String name = req.getParameter("name");
String sql = "select * from mooc.users where name like '"+name+"'";
try {
resultSet = statement.executeQuery(sql);
boolean flag = false;
while (resultSet.next()){
String entryName = resultSet.getString("name");
String entryEmail = resultSet.getString("email");
resp.getWriter().write(entryName + " has been taken by someone with the followint email: " + entryEmail);
flag = true;
}
if (flag)
return ;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
resp.getWriter().write("Your name is available;");
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String sql = "insert into mooc.users values(default, '"
+ req.getParameter("username") + "', '"
+ req.getParameter("email") + "')";
resp.setContentType("text/html");
try {
statement.execute(sql);
resp.getWriter().write(
"received username:<b>" + req.getParameter("username")
+ "</b>, with email: <em>"
+ req.getParameter("email") + "</em>");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
Server server = new Server(8080);
WebAppContext context = new WebAppContext();
context.setDescriptor("WEB-INF/web.xml");
context.setResourceBase("");
context.setContextPath("");
context.setParentLoaderPriority(true);
server.setHandler(context);
server.start();
server.join();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<servlet-name>Register</servlet-name>
<servlet-class>Register</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Register</servlet-name>
<url-pattern>/servlet</url-pattern>
</servlet-mapping>
</web-app>