Web Science/Part1: Foundations of the web/Dynamic Web Content/Ajax and the XMLHttpRequest class

Da Wikiversità, l'apprendimento libero.
Jump to navigation Jump to search

Ajax and the XMLHttpRequest class


Obiettivi di apprendimento

  1. be aware of JavaScript APIs
  2. know some of the standard JavaScript libraries
  3. be able to understand the concept of Ajax requests.





<head><title>Registration Form</title></head>
	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;
<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>
<label for="emailinput">Enter email</label>
<input name="email" id="emailinput" type ="text" />
<input name="submit" id="submitbutton" type="submit" value="register"/>



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 {
			// Setup the connection with the DB
			connect = DriverManager
							+ "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
		} catch (SQLException e) {
			// TODO Auto-generated catch block

	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
		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") + "')";

		try {
					"received username:<b>" + req.getParameter("username")
							+ "</b>, with email: <em>"
							+ req.getParameter("email") + "</em>");
		} catch (SQLException e) {
			// TODO Auto-generated catch block


	public static void main(String[] args) throws Exception {
		Server server = new Server(8080);

		WebAppContext context = new WebAppContext();


<?xml version="1.0" encoding="UTF-8"?>



<quiz display=simple> {What is true about using JavaScript for issuing an HTTP request from some webpage?} + Usually only HTTP requests to the domain from which the webpage that contains the calling JavaScript was downloaded are possible - It is possible to make HTTP requests to other servers if they run on port 433 + It is possible to make HTTP requests to other servers if they have a cross origin resource sharing policy + It is possible if the from which the webpage that contains the calling JavaScript was downloaded is white listed in the Access-Origin Header field of the server response. - If not allowed the browser will prevent JavaScript from making the HTTP request. |interestingly the request is made and only the response is dropped (this makes sense otherwise the Access-Control header of the response could not be processed by the browser SEND MAIL TO CHRISTOPH) - the repsonse has to be in JSON (JavaScript object notation) | No, the response can be in any format.

{Why is JavaScript usefull for the World Wide Web?} + It enables more interactive websites | even though HTML allows for input fields and text areas JavaScript increases the amount of interactivity + It can take loads of traffic from the web server or the web server's backend | yes for example if data needs to be sorted this can easily be done by the client - It can help websites to better communicate with search engines and provide metadata like RDFa | No indeed search engines frequently ignore JavaScript - Without JavaScript, the structure of web content could not be completely seperated from layout and formatting | JavaScript does not aim to support people to separate structure from layout and formatting + It can help to easily make asynchronous HTTP requests to a web server | This is useful since a webpage does not have to be assembled at the server which blocks but can rather be asynchronously assembled on the client side.

{What are the advantages of JavaScript libraries?} + They provide an API that will work on almost any browser | The most popular browsers and many different versions are supported by these libraries. - They make JavaScript more powerful | No, they don't change the expressiveness of JavaScript at all

{Which of the following are JavaScript libraries} + jQuery - PHP - Java + mootools + Prototype - Netscape