Comm Lab Networked Media Week 4

HTML Forms

Forms allow the page to take input from a user and send it to a server for processing. Also, using JavaScript the page can be made responsive or interactive by respond to form related data or events.

Putting a form on a page is as simple as using the various form tags nested within a <form> element.

	<form>
	
	</form>

Form Elements

Input

There is an entire class of input type form elements Text Field:

<input type="text" name="textfield" value="The Value" />
Allows text to be entered. The "value" attribute can be used to specify a default value.

Hidden Field:

<input type="hidden" name="hiddenfield" value="The Value" />
Allows a value to be in the form but not displayed to the user. The "value" attribute specifies the value.

Button:

<input type="button" name="pushbutton" value="Button" />
Button that can be pressed by the user. The "value" attribute is what displays on the page. Generally this is used to trigger an event that will call some JavaScript.

Submit:

<input type="submit" name="submitbutton" value="Submit" />
A button that is used to submit the form to the server. The "value" attribute is what display inside the button.

Reset:

<input type="reset" name="resetbutton" value="Reset" />
A button that is used to reset the form to the state it was when loaded. The "value" attribute is what display inside the button.

Radio Buttons:
Radio 1:
Radio 2:
<input type="radio" name="radiobutton" value="Radio 1" />
<input type="radio" name="radiobutton" value="Radio 2" />
A series of radio buttons that allow the user to choose between a series of options. Each one has the same "name" attribute but a different "value" attribute.

HTML 5 Input Elements

With HTML 5 came a whole new set of input elements Color:

<input type="color" name="somecolor">
Allows the user to select a color using a standard color picker.

Range:

<input type="range" name="arange" min="0" max="10">
Allows the user to input a possible range of values.

and a whole bunch more: HTML5 Input Types

Other Form Elements

Select List:

<select name="selectlist">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
</select>
A drop down list of options that allows the user to select one. Multiple selections can be enabled by adding the keyword "multiple" in the "select" tag.

Form Actions

One of the nice things about forms in HTML is that you can execute JavaScript when information is selected or typed into the form. The best way to do this is to add an event listener to the form element itself.

For instance, form elements support a whole slew of different events: HTML Event Attributes (look for Form Events).

Each of these events can be listened for by adding an event listener
	<input type="text" name="something" id="inputfield" />
	<script type="text/javascript">
		document.getElementById('inputfield').addEventListener('keypress', function() {
			alert('you pressed a key');
		});
	</script>>
a good one to use is typically 'change'
	<input type="text" name="something" id="ainputfield" />
	<script type="text/javascript">
		document.getElementById('ainputfield').addEventListener('change', function() {
			console.log(document.getElementById('ainputfield').value);
		});
	</script>>
for buttons and the like, you probably want to use a 'click'
	<html>
		<head>
			<title>Button Function</title>
			<script type="text/javascript">	
				function buttonPushed()
				{
					document.write("Why did you do that?");
				}
				
				function init() {
					document.getElementById('abutton').addEventListener('click', buttonPushed);
				}
				
				window.addEventListener('load', init);
			</script>
		</head>
		<body>
			<form>
				<input type="button" name="abutton" id="abutton" value="Do NOT Push Me" />
			</form>
		</body>
	</html>

Web Services

AJAX

AJAX (Aysnchronous JavaScript and XML) is a technique for dynamically altering a page after communicating with the server and without leaving the page.

Essentially it is made possible by the XMLHttpRequest object

AJAX is a bit difficult to get working in a cross platform manner but their are quite a few libraries out there that have done the hard work.

p5.js has a nice set of AJAX functionality built-in that we can access through the loadStrings method:

Here is a quick example: A text file on the server named ajax_example.txt:
		Something...
		
The HTML (named ajax_example.html):
<html>
	<head>
		<title>AJAX Example</title>
		<!-- Load up the AJAX External JavaScript file -->
		<script type="text/javascript" src="p5.js"></script>

		<!-- Local Javascript Functions and so on -->
		<script type="text/javascript">

			// A variable to hold the interval id
			var interval = null;	
	
			// A function to call our AJAX PHP script
			function call_ajax()
			{
				loadStrings('ajax_example.txt',ajax_return);
			}

			// A function that gets called when ajax returns
			function ajax_return(response)
			{
				document.getElementById("messages").innerHTML = response;
			}
	
			// Setup AJAX function, creates a timeout so that we run something periodically
			function setup_ajax()
			{				
				// Set interval of 5000 milliseconds
				// Keeps going...
				interval = setInterval(call_ajax,5000);

				// Only happens once..
				//interval = setTimeout(call_ajax,5000);
			}			
		
			// Register setup_ajax with the onload event of the window (when it is done loading)..	
			window.addEventListener('load', setup_ajax);

		</script>
	</head>
	<body>
		<b>Looky here!</b>
		<div id="messages" style="overflow: auto; width: 500px; height: 400px;">
			Something should pop up here..
		</div>
	</body>
</html>
		
The above example is very simplistic but a illustrates many points. First of all, the browser loads the HTML and executes the JavaScript contained within ajax_example.html. At the bottom of the JavaScript there is an "window.addEventListener" for the "load" event which is assigned to run a function called "setup_ajax". This ensures that the "setup_ajax" function will run after the HTML page is rendered and the JavaScript functions are all defined.

The "setup_ajax" function creates an interval (something that happens over and over again) that calls "call_ajax" every 5 seconds.

The "call_ajax" function is where we call "loadStrings" which is a function defined in "p5.js". This function takes in the URL of the page to call, in this case "ajax_example.txt" and what function to send the source of this page to ("ajax_return").

Essentially, "loadStrings" is functioning as if someone clicked on a link but instead of going to a different page in the browser, the source code of that page get's sent to a JavaScript function. This enables us to modify a page on the fly, perhaps even "live"..

The "ajax_return" function takes in the source of the page that was called and in this case just uses the getElementById and innerHTML methods and properties to modify the current page.

Taking this a step further, we could modify the text file that is being called repeatedly by the AJAX at any time and the change would be reflected on the user's browser.

Consequently we could make a platform which enabled many people at once to experience changes to a file on the server. This could be the basis of a chat room or any other live platform that we choose.

Add in a bit of server side programming and the sky is the limit.

More Information: A Brief History of Ajax by Aaron Swartz

JSON

JSON stands for JavaScript Object Notation. It has become a standard way to provide machine readable data to and from web services. Despite the fact that JavaScript is part of it's title, it is generally useful in all programming languages.

(XML - Extensible Markup Language is another popular means for providing machine readable data to and from web services.)

As stated on the json.org site: An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).

A simple JSON object

{
	fist_name: "Shawn",
	last_name: "Van Every
}		
		

An array of JSON objects

[
{
	fist_name: "Shawn",
	last_name: "Van Every"
},
{
	fist_name: "Joe",
	last_name: "Frank"
}		
]		
values can be string, number, null or boolean (true/false)

One JSON data feed that might be interesting is from OpenWeatherMap. Their API is documented here.

This is the feed for New York City's data: http://api.openweathermap.org/data/2.5/weather?id=5128581&units=imperial which yields the following:

{"coord":{"lon":-74.005966,"lat":40.714272},"sys":{"country":"US","sunrise":1380106043,"sunset":1380149242},"weather":[{"id":800,"main":"Clear","description":"Sky is Clear","icon":"01n"}],"base":"gdps stations","main":{"temp":60.44,"pressure":1013,"temp_min":54,"temp_max":66.2,"humidity":88},"wind":{"speed":2.22,"gust":3.08,"deg":285},"rain":{"3h":0},"clouds":{"all":0},"dt":1380076310,"id":5128581,"name":"New York","cod":200}
		

We can make this JSON easier to read by doing some formatting: http://jsonformatter.curiousconcept.com/

After formatting we get the following:

{
   "coord":{
      "lon":-74.005966,
      "lat":40.714272
   },
   "sys":{
      "country":"US",
      "sunrise":1380106043,
      "sunset":1380149242
   },
   "weather":[
      {
         "id":800,
         "main":"Clear",
         "description":"Sky is Clear",
         "icon":"01n"
      }
   ],
   "base":"gdps stations",
   "main":{
      "temp":60.44,
      "pressure":1013,
      "temp_min":54,
      "temp_max":66.2,
      "humidity":88
   },
   "wind":{
      "speed":2.22,
      "gust":3.08,
      "deg":285
   },
   "rain":{
      "3h":0
   },
   "clouds":{
      "all":0
   },
   "dt":1380076310,
   "id":5128581,
   "name":"New York",
   "cod":200
}
		

We see a lot of what we might expect, temp, pressure, humidity and so on. Also of interest is the sunrise and sunset time. These are particularly interesting because they are represented in standard "unix timestamp" which is the number of seconds from January 1, 1970. http://www.epochconverter.com/ - Command line: date "+%s"

To pull a value out of this JSON structure, we simply treat it like it is a javascript object and use dot syntax to traverse through the structure. To get the current temperature, we use the top level object and keep going down, theObject.main.temp should contain the current temperature.

		
			var theObject = {
			   "coord":{
				  "lon":-74.005966,
				  "lat":40.714272
			   },
			   "sys":{
				  "country":"US",
				  "sunrise":1380106043,
				  "sunset":1380149242
			   },
			   "weather":[
				  {
					 "id":800,
					 "main":"Clear",
					 "description":"Sky is Clear",
					 "icon":"01n"
				  }
			   ],
			   "base":"gdps stations",
			   "main":{
				  "temp":60.44,
				  "pressure":1013,
				  "temp_min":54,
				  "temp_max":66.2,
				  "humidity":88
			   },
			   "wind":{
				  "speed":2.22,
				  "gust":3.08,
				  "deg":285
			   },
			   "rain":{
				  "3h":0
			   },
			   "clouds":{
				  "all":0
			   },
			   "dt":1380076310,
			   "id":5128581,
			   "name":"New York",
			   "cod":200
			};
			
			console.log("Temperature is: " + theObject.main.temp);
		
		

Using AJAX to load JSON

Unfortunately, there are quite a few security restrictions on making AJAX requests across domains. If you are interested in investigating those and how to overcome them, checkout this: http://www.html5rocks.com/en/tutorials/cors/.

Fortunately, since we are using libraries such as p5.js we don't have to worry so much. (I hope)

p5.js to load JSON

Using loadJSON:
function setup() {
  loadJSON("http://api.openweathermap.org/data/2.5/weather?id=5128581&units=imperial",jsonLoaded);
}

function jsonLoaded(theObject) {
  	console.log("Temperature is: " + theObject.main.temp);  
}

jQuery to load JSON

<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
	$(document).ready(function(){
		$.ajax({
		  url: "http://api.openweathermap.org/data/2.5/weather?id=5128581&units=imperial",
		  dataType: 'json',
		  success: function(data) {
			alert("Temperature is: " + data.main.temp );
		  },
		  error: function() {
			alert("error");
		  }
		});        
	});
</script>