# Web Programming/Printable version

The current, editable version of this book is available in Wikibooks, the open-content textbooks collection, at
https://en.wikibooks.org/wiki/Web_Programming

# Web and Web Programming
## The Web and the Internet

What is the Web? Known as the World Wide Web the web is an application or service running on the Internet, which is the infrastructure (information superhighway - a delivery mechanism). The Internet is a interconnect global network of computer networks, which is like a postal system which allows us to deliver mail pieces of all kinds with "the web" as one of them. Initially the web is designed to be a distributed hypertext document sharing system. Now it has evolved to become a platform for distributed applications. Think about all the web applications you use, e.g. Google search engine, Amazon web store, and Youtube.

## The Client-server Model

The Web is based on a simple client server model. As shown in the figure a client sends a request and the server responds by sending a response back.
It is a rather simple model, but we can build powerful application with this simple model.
Both clients and servers are software entities but both run on hardware platforms. The same hardware platform can have multiple software entities running on it. Normally a web client is a web browser, e.g. IE, Firefox, or Chrome, and a web client is a web server, e.g. Apache and IIS. The boundary between a web client and a web server is blurred when a web server consumes web services offered by other web servers and hence become a client to them.
Every web application has two components: the client side and the server side. There are programming frameworks (e.g. Google App Engine) available for writing web applications as one piece by automatically generating the client side. We will manually manage the two components to get a better understanding of web basics.

### HTTP

HTTP stands for the Hypertext Transfer Protocol, which is an agreed upon standard (set of rules) for communicating on the web. It is like a language and any program that speaks the language can be a member of the web as a client, a server, or both. Each service that runs on the Internet has its own protocol, such as IMAP for email retrieval, FTP for file transfer, and SNMP for managing networks.

### API

You don't need to master the HTTP protocol in order to create web applications. Web APIs (Application Programming Interface) allows us to focus on the application logic by abstracting away the details of the common tasks (plumbing). As shown in the figure an API provides a higher-level abstraction of the detailed mechanisms.
The browser works as a user agent firing HTTP request on human users behalf. For instance, when a user clicks on a hyperlink the browser sends HTTP request. The request can be a GET request, e.g. fetching a new page, or a POST request sending (form) data to a server. We, as programmer, can also send requests by calling functions (part of API provided by the browser) in the client code, which runs in the browser.

### URL

URL (Uniform Resource Locator) is also known as web address. Any resource available on the Web is identified by an URL, which has to be unique globally.
The following figure shows an example URL pointing to a file (resource) on a web server:
When the URL is sent to the server, the server will map the rest of the URL - /~blu/helloworld.html - to a path in the server's file system: /home/blu/public_html/helloworld.html. In other words, whatever is after /~blu/ gets appended to /home/blu/ to be used to find the resource (file) on the server.

### "Hello World!" Example

In the previous example, if the following text is in the helloworld.html file you would have seen the text appeared in the browser window after you typed in the URL in the address bar and hit enter.
Hello World!
Sending a URL via a browser triggers a GET request to the server for the resource identified in the URL. The response to the request is the content of the file. This is the simplest example showing how the client-server model works.

# HTML

Objectives:
* design and structure web pages using correct HTML tags, such as paragraph, heading, list, and image
* draw a page by tracing its HTML source code
Resources:
* slides for chapter 2
* Tutorials on w3schools
* HTML tag reference
* 198.209.19.99/~blu/book_examples/ch02-html-files/all_examples.html
* a short wikibook on HTML

# What is HTML?

HTML (HyperText Markup Language) is the standard language for defining web pages, which serve as the interfaces to your web applications. HTML files are plain-text files following the HTML syntax. A browser knows how to take an HTML file and display in a browser window the page defined by the HTML file. The file can be stored locally on the computer the browser is running on or fetched from a web server using a URL. Creating HTML files is coding because the result source code gets executed by a browser, which is a virtual machine.

# Tags Define the Page Structure

An HTML file consists of content marked-up by tags as shown in this picture:
The tag at the beginning of the file is special as it is used to indicate the standard the file is following. <!DOCTYPE html> means HTML5 - the latest HTML standard, which some new features. You can copy and paste this tag to every HTML file you create.
Most tags appear in pairs - an opening tag and a closing tag. Each pair of tags defines an element for the web page, which can be visible or invisible. The visible elements are like boxes. All boxes hold some content and some boxes can contain other boxes. For instance, the <html></html></html> defines the root (highest level) element, which should enclose everything else in your HTML file. Inside the "html" element we have a "head" element and a "body" element defined by their corresponding tags. Inside the "head" element is a "title" element and inside the "body" element is a "paragraph" element defined by the
tag pair. Both the "title" element and the "paragraph" element have text as their content. This type of nested structure resembles a tree. In fact, a browser always parse an HTML file first into a DOM object (a tree data structure) before it draws the page on the screen. Note that
tag defines a comment, which is used for documentation and has no effect to the page. The figure to the right depicts the tree structure defined by the nested tags in the HTML file.
We call elements that enclose other elements parent elements and enclosed elements children elements. Obviously a child element must be completed enclosed in its parent element, which means the tags must be properly nested. For instance, the following HTML fragment is confusing to a browser because the two elements are intermingled:
We call elements block elements if they can contain other elements. For example, a paragraph (<p>) element and a list (<ul>) element are block elements and they usually occupy multiple lines on the page. All other elements are called inline elements. Some tags are self-closing, e.g. the <br/> defines a linebreak, which is necessary because all space characters in HTML are ignored by browsers. Some tags allows us to define additional attributes for the elements, e.g. <img src='MyPicture.jpg' /> defines a image at location specified by the "src" attribute. Each attribute is a name and value pair with the value in double quotes. As you can see from this example, images are embedded into web pages by using the <img /> tag that points to the images and the actual images are not part of the HTML file. This is an example of an external component, which also includes CSS and JavaScript files. Such external components must be downloaded separately and incorporated into the web pages.
Here is an example showing all kinds of elements and what they appear on a web page. Right click on the page and select "view source code" to see what's inside the page's HTML source file.
The best way to learn HTML is to study examples and tweak them to meet your needs. Our goal is to be able to draw mental pictures of a page by looking at the HTML source file. In other words we want to understand the relationship between what we write in an HTML file and what will appear on the page so that we can imagine and create web pages.

# Essental Tags

You can find a comprehensive list of HTML tags at W3C schools. More specifically you need to know how to use the following tags (click on a tag to see a description and example use of the tag).
* <!DOCTYPE html>
* <a>
* <audio>
* <abbr>
* <blockquote>
* <body>
* <br>
* <dl>
** <dt>
** <dd>
* <em>
* <head>
* <h1>-<h6>
* <hr>
* <html>
* <img>
* <ol>
* <ul>
** <li>
* <link>
* <p>
* <q>
* <style>
* <table>
** <tr>
** <th>
** <td>
* <video>

# Meta Tags

In the head element a number of meta tags can be used to provide information about the HTML document as show in this example.
The meta tag with "charset" attribute is required. The attribute is commonly set to "utf-8" as shown this example.

# HTML5 Semantics

HTML5 introduces a number of semantic elements to help search engines or other programs better identify the structure of a web page.
* <header>
* <section>
* <article>
* <nav>
* <aside>
* <footer>
* <time>
* <figure>

# CSS

Objectives:
* style common properties of HTML elements using basic CSS rules
* identify the order in which CSS rules are applied
* resolve conflicts in the rules
* draw web pages by tracing HTML and CSS source code
Resources:
* slides for chapter 3
* Tutorials on w3schools
* CSS reference on w3schools
* 198.209.19.99/~blu/book_examples/ch03-css-files/index.html

## CSS Syntax

CSS stands for Cascading Style Sheet. A CSS file is an external/additional file attached to an HTML file for styling the web page. Note that the syntax for CSS files is different from the HTML syntax. A CSS file consists of a set of rules, when applied, will affect the look and feel of the page it associates with. Each rule starts with a selector that will select a number of elements on the page and the body of the rule specifies which property should have what value. The general format of a CSS rule is as follows:
The following example rule selects all paragraph elements and set the text color to red and center align the text in the paragraphs.
You can see a running example at .
As shown in the example, the body of a rule can have a number of statements/declarations terminated by ";". Each statement is a property name and value pair (delimited by a ":").
There are three ways of attaching a style sheet to a file:
* external style sheet file (pointed to by a <link /> element in the <head>)
* internal style sheet (as a <style> element in the <head> )
* inline style (as attributes of elements)
The following example shows how an external CSS file is linked to an HTML. For other examples visit CSS Howtos.

## Commonly Used Properties
### color

See different way to set font color in this example.

### font

You can use this site to find all supported font families in your browser.

## Style Text
### position

* text-indent
* text-align
* vertical-align

### decoration and transformation

* text-decoration
* text-transform

### CSS3 shadow

* text-shadow

### float image

* float

## Cascading Rule

CSS rules can also be embedded into HTML code as the "style" attribute (inline style) for tags or as a script element in the head element. What happens if we have multiple rules specified in different places but all of them affecting the same element on the page? This is where the cascading (precedence) rule comes play. The following are CSS locations in a descending order in terms of their priorities:
* rules in the style attribute of a tag
* rules in the script elements in the head
* rules in an external CSS file
* rules inherited to from parent elements
* rules known to the browser as default
For example, the inline styles will always take precedence over other styles. If there is no inline style set for an element the browser will attempt to use CSS rules in the script element.
When two rules from the same location set the same property to different values it is a conflict, which is resolved by letting a more specific (tightly matching) rule override a more general (or inherited) rule and if the two rules match equally tightly the one appears last in the source to take effect.
* rules set by id selectors are most specific.
* rules set by class selectors, attribute selectors, or pseudo-class selectors are less specific.
* rules set by tag selectors or pseudo-element selectors are the lest specific.

## CSS Pseudo-classes

Pseduo-classes allow us to apply styles to elements at a particular state, for instance the following rule only takes effect on the selected elements when they are moused over. Check out this reference for details.

## CSS Pseudo-elements

A CSS pseudo-element is used to style specified parts of an element. The following two examples are in CSS2 and CSS3 syntax respectively. Check out this reference for details.

## CSS3

CSS2 added new selectors, such as nth-child, inline-block, :not, +, and the ability to embed fonts in a page. It also provides built-in support for multi-column layouts, transparency/opacity, color gradients, shadows, rounded corners/borders, border-radius, animations/transitions, and affine transformations (scaling, rotation, perspective).

### CSS3 Colors

CSS3 provides three new ways to specify colors. Check out this reference for details.

# Layouts

Objectives:
* use CSS rules to change the default layout of a page
* identify the difference between different positioning
Resources:
* slides for chapter 4
* Tutorials on w3schools
* CSS reference on w3schools
* 198.209.19.99/~blu/book_examples/ch04-layout-files/index.html

# Box Model

When a browser renders an HTML file, it puts each block element in a box, which allows us to change the size , the border, and the spacing within (and without) of the box. This is known as the box model.
Each box has the following property we can set: the dimension of the content area (height and width), the padding, the border, and the margin.
Layout determines the relative position of the elements/boxes on a page. The default layout (document/normal flow) simply stack the block elements and use a "flow layout" to position the children elements in a parent element. This is the default way to determine the positions of the elements.
There are three methods to change the default position of an element: aligning, floating, and positioning. To relocate an element to a desired position, we should try to use alignment first because it is the simplest method and try using positioning last as it most obtrusive.

## size

* width
* height
* mid-width
* max-width

## align

To horizontally align content in a block element we can set the text-align property for the block element. The vertical alignment of an inline element within its containing element can be changed by setting the vertical-align property for the inline element. The inline element should be aligned vertically with respect to other content on the same line within the same containing element.
Block elements can be center on page by setting their width property and set their left and right margins to "auto".
A block with its width set can be pushed to the left or to the right by making it float.

## spacing

* margin
* padding

## border

* border
* CSS3 border-radius
* CSS3 box-shadow

## background

* background

## position

The CSS positioning properties allows us to set an element with offsets relative to a reference point, which differentiates the four positioning methods.
* static: default position
* absolute: relative to the containing element, which must have the position property set to a non-default value ((example1 example2)
* relative: make the absolutely positioned children elements relative to this element (example)
* fixed: relative to the browser window (example)
The offsets can be left, right, top, and bottom.

# Page Layout

You can use the float property to take an element out of the normal layout (flow ) and push it either to the left or the right. The element's vertical position is the same as the vertical position it would be in the normal layout. If a float element is above some text, the browser will wrap the text around the floating element. A floating element normally have its width property set because otherwise it would take the available horizontal space appearing not floating.
A floating child element stays inside its parent element, i.e. the enclosing relationship, which is physical, doesn't change. A floating child element may hang out of its parent's box because it doesn't take into account the floating children elements. The overflow property determines what happens when the content overflows an element's box. The clear property, when set on an element, will push the element down to avoid ("stay clear") of floating elements to the left or to the right.
To create multi-column layout we can use float and clear elements.
* float
* clear
Here is an example.

# Alignment v.s. Floating v.s. Positioning

* if possible, lay out an element by aligning its content
** horizontal alignment: text-align (aligns the content of a block element with this property)
** vertical alignment: vertical-align (aligns an inline element with this property within its containing element)
* if alignment won't work, try floating the element
* if floating won't work, try positioning the element
** absolute/fixed positionings are a last resort and should not be overused

# PHP

Resources:
* book chapter
* PHP 5 Tutorial
* PHP 5 Reference
* PHP Project Homepage
PHP (stands for PHP Hypertext Preprocessor) is a programming language for processing web requests. When you use a browser to request or fetch a web page you are sending a request to the server. The web server know how to use the URL to find the file and send it back to your browser. PHP allows us to create programs on the web server and when the programs are requested the server send the output from the programs as the response. For this to work, the web server must know how to handle PHP files. Most web servers have the PHP module installed and when they see a request for a PHP file they will forward the request to the PHP module. The PHP module will parse the request parameters and invoke the requested PHP code.
This is a powerful idea. With PHP you can create programs on a web server that can dynamically create web pages using data sources from files to databases to other web services. Even though it is a simple request-response model on top of the web client-server model, we can be create powerful web applications by breaking down complicated interactions to a series of request-response cycles.
PHP is a scripting language. We create our programs as text files, which are also the executables. When a program is executed the PHP interpreter reads the source/executable file and execute one line of code at a time. Your PHP code can be tested on the server by using the interpreter as follows:

## PHP Basic Syntax

In a PHP file you can intermix PHP code and static content. When the file is executed only the PHP code gets executed. The output from the code replaces the code part forming the output of the program with the static content intact. This design makes it easy to generate web pages using a template and injecting dynamic content into parts of the page.
A PHP code block is defined using a tag as shown in the example:
Please check out the following tutorials on w3schools.com to learn basic PHP syntax:
* code block and comment
* variables
* echo and print
* data types
* operators
* if-else
* switch
* while/do-while loop
* for loop

### Examples

The HTML generate by the previous PHP script is as follows:
The indentation is not what we expected and we could print the space or the tab characters from the PHP script but it would be very tedious. Instead we can use expression blocks to inject dynamic contents to the static ones as shown in the following example.

## PHP String Functions

Functions are reusable blocks of code. PHP has a set of build-in string functions for manipulating strings. A partial list of string functions is as follows:
* strlen
* strpos
* substr
* strcmp
* explode
* implode
* complete list of string functions.
The explode function allows us to "unpack" a string into a array of substrings. The following code
will output
You can name the substrings using the list notation. The following code
will output
The implode function packs a array of strings into a single string.

## PHP Array Functions

Python array allows us to refer to a collection of items using a single variable. The items can be of any datatype including array (how multi-dimensional arrays are created). The size of a Python array is not fixed. In fact there are functions that allow you to treat an array as a queue or a list. Some example array functions are as follows:
* array
* count
* list
* array_push
* array_pop
* array_slice
* array_splice
* array_shift
* array_unshift
* sort
* rsort
* complete list of array functions

## PHP Global Variables

PHP superglobal variables are a set of predefined variables that are always accessible to all PHP scripts on the server.
They are:
* $GLOBALS
* $_SERVER
* $_REQUEST
* $_POST
* $_GET
* $_FILES
* $_ENV
* $_COOKIE
* $_SESSION
The following script
will output content similar to
As you can see the server gets all kinds of information from the client through the HTTP request sent and makes the information available to the PHP scripts via the $_SERVER variable.
If we request the following script using the following URL: http://host/path/to/test.php?first_name=Curious&last_name=George the script will echo back the parameters sent via this request.
The actual output is
$_REQUEST is an associative array with strings as indices. You can refer to the elements in the array by their names, for example $_REQUEST["first_name"] will give you the value of "Curious". If you expect a parameter to be sent to your script via the query string you can attempt to get it through this $_REQUEST variable. The following script test whether the parameter is sent and echoes "first_name parameter is missing." if the parameter is not provided in the query string.

## PHP File Functions

PHP file functions allows us to access and manipulate the filesystem on the server on which our PHP scripts are executed. The basic file functions include reading content from a file or a directory and writing to a file. Some commonly used file functions are as follows:
* file
* file_get_contents
* file_put_contents
* glob
* basename
* complete list of file functions
The following PHP script reads a poem from a file and outputs it as a ordered list.
The output will appear as follows in a browser window:
Reading a directory is similar to reading a file except that the result is a list of files and directories of the directory we are reading. The glob function allows us to scan a directory to read items (file or directory) that matches a pattern. The following script reads names of text files that are in the "word" subdirectory, which is under the directory that contains the script.
As shown in the output below the array returned from the glob function contains relative paths to the files, which makes it easy to read the files (next example).
The next script takes the paths to the files, reads the file contents, and echoes them back to the caller.
A sample output of the script is as follows. The basename function returns the path's last component, which is the "bare" file name.

## PHP Include Statement

PHP include statement copies the content of another file into the current file where the include statement appears. For example, the following statement will "include" the output of the navigation.php script (e.g. HTML code for a navigation bar) into its own output.

# Forms

Resources:
* book chapter
* HTML forms tutorial on w3schools
* references on w3schools
* responsive web design tutorial

# Form Syntax

A web pages represents the interface of our web application and the backend scripts (e.g. PHP) implements the application logic. We must collect user input from the interface and send them to the application logic. HTML input controls are elements that collect user input and the form element can be used to send the data to the backend. Later we will learn how to submit the input programmatically using JavaScript.
Common input controls include text field, text area, drop-down list (select), checkbox, radio button, reset button, and submit button. Detailed usage and examples can be found in the following list:
* form tag
* <input /> tag
** textfield example
** button example
** checkbox example
** radiobutton example
** submit button example
* <textarea> tag
** textarea example
* <select> tag
** <option> tag
** <optgroup> tag
** drop-down list example
* <label> tag
** label example
* <fieldset> tag
* <legend> tag
** fieldset with legend example

# Example

Lets add add and delete functions to our todo list web application. Recall that we use a text file to store todo items with each item on a separate line. To add a new todo item to the list we must collect the new item as a user input, send it to a script on the server, and append the new item to our existing list of todo items.

## Add TODOs

We can use a add.php output an HTML form and ask it to submit user input in the form to add_submit.php.
In the following add_submit.php script we get the value for the parameter (todo) and append it to the text file if the parameter is sent and has non-space characters in it. At the end of the list we include the list.php to output the current todo list as a feedback to the user. Note that once a user submit a new todo item the response will be displayed on a another page (add_submit.php), which doesn't include the form. If the user wants to continue adding new todo items, she will need to click on the back button, which in inconvenient.
In fact we could combine the two scripts into one so that users will see the add form and the current list all the time and be able to add new todo items. We will rename our script to todo.php.
Note that the "\n" appended to each new line is important because we want each todo item in its separate line in the todolist.txt file. When requested this script will always output the add form and the current list (via list.php). If a parameter named "todo" is sent and it is not empty the value of the parameter will get appended to the todolist.txt file. A screen shot of the page generated by todo.php is as follows:

## Delete TODOs

In this next step we will allow users to delete individual todo items in the list. We need to modify the user interface (web page) for users to trigger the delete actions. When a link is click on a page the browser sends a request to a resource on the server identified by the action URL. We could add a delete link after each todo item and use it to trigger the deletion of the item. We will also need to create a script on the server to respond to such requests. The script needs to know which todo item a user wants to delete. Somehow each request needs to be specific to each item. We learned previously that we can append a query string to the URL of a request to parameterize it. The question now is what the parameter should look like. As each todo item is stored in the todolist.txt file as a line of text we can delete any todo item by deleting its line in the text file if we know the line number. The following script tests the idea of deleting a line by its line number. The line number is hardcoded, but eventually we want to get it as a parameter sent from a browser. The usage of the functions used can be found in the list following the code.
* isset
* file
* implode
* array_splice
* file_put_contents
On the client side (in the HTML file) we can use URLs of the following format to send the line number. The name of the parameter "line_number" and value will be the actual line number for a particular todo item.
We will need to revise the list.php file to output the delete links.
The modified web interface should look as follows:
The HTML source code looks as follows:
As you can see the values of the "line_number" parameters corresponds to the actual line numbers of the items in the todolist.txt file. Now whenever a delete link is clicked on the delete.php script will receive a request with a line_number parameter. We can now modify our delete.php script to handle such delete requests.
Note that the delete links points to a file different from todo.php (outputs our main page) causing browser to land on the empty delete.php page because it outputs nothing.

# One Page Application

It would be nice if we can stay on the same page (todo.php). The following code shows the whole application in one script:
The static HTML at the beginning of the file output the add form. The first if block handles the add function. The second if block handles deletion. The for block list the todo items currently in the list. Note that all URLs in the output from this file point to the todo.php script.

# Responsive Web Design
## External Resources

* Bootstrap tutorial on w3schools

# JavaScript

Resources:
* slides on JavaScript
* slides on jQuery
* JavaScript tutorials on w3schools.com
* JavaScript references on w3schools.com
* JQuery tutorials on w3schools.com
* JQuery references on w3schools.com
* jsfiddle
* JQuery
* JavaScript: Understanding the Weird Parts - The First 3.5 Hours
JavaScript is a scripting language. When attached to a webpage (HTML) it is interpreted by a web browser and can be used to manipulate the webpage by responding to various events. Traditionally JavaScript runs on the client site to create dynamic behaviors, such as form validation, to make a page more interactive. Recently JavaScript is increasingly being used to make asynchronous web requests (ajax) and handle web requests on the server (node.js).

# Life Cycle

Hello world A JavaScript program is a plaintext file with JavaScript code. When the script file (code) is loaded a JavaScript interpreter parses statements in the file sequentially and carry out the operations. If a statement defines a function the interpreter remembers the definition and only executes the function when it is called. The following JavaScript code defines one function, which uses the alert function to say "Hello". When the script is loaded it executes one statement, which invokes the sayHello function, and then it executes what is in the function definition.
A client-side JavaScript file is always attached to an HTML file, which allows the script access to the object (DOM) that represents the page. Often times the first thing we do in the script is to attached functions to the page elements to handle various events. The following HTML code defines a button and includes a demo.js to make the page interactive by handling events.
The demo.js file has the following content.
In the script the implicit window object is used to attached a event handler to the onload event, which takes place when whole web page finishes loading. The event handler is defined as an anonymous function, which is fine because the function is only referenced once. In the function we use the implicit document object (representing the page) to find the button object by its ID and attached the sayHello function to handle the button's click event. Note that the first three lines of code is a single statement, which is why it needs to be terminated with ";". The anonymous function is not executed till the whole page is loaded and the sayHello function is not executed till the button is clicked. We have to wait for the page to finish loading before we can attached event handlers to page elements because the elements have to exist before we can reference them.
The script can be included in the HTML directly as follows. This is OK, but it doesn't cleanly separate the content (HTML) and the behavior (JavaScript) and hinders code reuse (you can not use the script on other pages). I will use this style in future examples because the code stays in one file in compact form.

# DOM

The "document" in the previous example points to a DOM (Document Object Model) object that represents the webpage. In fact, before a browser draws a page on the screen it has to download the HTML code that defines the page, and then constructs a DOM object in memory for the page. So the DOM object for a page is the underlying data structure for rendered page on the screen. We can modify the page on screen by changing its DOM object, for example modifying the content or the style of an element, adding a new element, and removing an element.
In the next example we say hello by changing the content of a paragraph instead of using a popup window, which can be disturbing. The paragraph element has property called innerHTML representing its content. We can change this property to change the content of the paragraph on the web page.

# Events

In addition to the onclick event there are many other events we can choose to handle. Most of the events are triggered by user actions. Sometimes we want to programmatically trigger a event with a delay or periodically. The following example uses a timer to delay the calling of a function. The setTimout function takes two parameters: the first one is the name of function we want to call when the timer expires and the second parameter specifies the delay in milliseconds.
It would be more interesting to animate the count down on the page, which means we need to update the content of the paragraph periodically. We can set the timer with an interval and clear it when the count reaches zero. This idea is demonstrated in the next example.
We can build a complete stop watch using this idea.

# jQuery

jQuery is a JavaScript library that extends the features of "native" JavaScript. It is the most popular JavaScript library because it
* simplifies DOM manipulation,
* allows element selection via CSS selector,
* addresses browser incompatibility issues,
* offers functional programming abilities (map an operation to a set of elements),
* offers method chaining by returning the caller object from most functions.

## Syntax

Simple syntax rules can be found at
* basics
* statements
Common utility methods include
* string methods
* array methods
* math methods
* date/time methods
* regular expression
Some interesting constructs include:
* for each loop
* toArray method
* method chaining
is a shorthand expression for
Any code that depends on a fully loaded page needs to go into this function.
The following is called a immediate function that run immediately without waiting for the document to become ready: a function is defined and called upon in a single statement.

## Element Selection

jQuery provides a much richer API for selecting HTML elements in almost all possible ways you can imagine. Most selectors are described at http://www.w3schools.com/jquery/jquery_selectors.asp and you can find a comprehensive demo at http://www.w3schools.com/jquery/trysel.asp
A jQuery selector finds/selects a number of HTML elements, on which we can apply operations.

## DOM Manipulation

jQuery makes DOM manipulation easier by providing a rich set of methods we can use. The following are the main categories of such methods:
* get contents and attributes: with multiple elements selected the method concatenate the contents/attributes and return a single string.
* set contents and attributes: we can set the same value to all selected elements or use a callback function to set different values based on the indices of the elements in the selected elements.
* add new contents or elements: the $('<tag>') method can create an element with any tag name.
* remove contents or elements: a selector can be used to filter the elements to be removed.
The following example generates a new square (div) and added to a parent container when the button is clicked.

## CSS Manipulation

The ideal way to manipulate style information is to define CSS classes and change the styles of elements by adding them to a class or remove them from a class: get and set CSS classes.
jQuery also provides a general-purpose .css function for manipulating individual CSS properties directly: css method. When the css method is called with one parameter, it gets a property with the same name as the parameter. When it is called with two parameters, it sets the property with the value as the second parameter. When the css method is called on a set of selected elements it behaves differently depending on whether it is a get or a set: get returns the property value of the FIRST selected/matched element and set changes the property values of ALL selected elements.

## Event Handling

jQuery is designed to respond to all kinds of events on an HTML page.
* events
* event methods and attributes

## Effects

The following effects can be achieved using jQuery:
* hide and show
* fade
* sliding
* animation

## jQuery UI

jQuery UI is a collection of GUI widgets built with jQuery, HTML, and CSS. A getting started guide can be found on jQuery learning center.

# AJAX

Resources:
* Introduction to AJAX
* Ajax with JQuery
Each web applications has at least two parts: a client side and a server side. The client side runs in the browser serving as the user interface of the web app. The server side run on a server, which allows app to implement the business logic and have access to various resources, e.g. the file system, databases, or other services. The interactions between the client side and the server side are in the form of requests and responses. Traditional a request is triggered when the user types a new URL in the address bar or click on the page. The response to the request would be a new page. Before the new page arrives the user has nothing to interactive. Such delays can be caused by network latency or server issues, which are hard to control. To offer good user experience our app should stay interactive at all times. Refreshing the whole page to respond to every request is highly inefficient because often time only a small portion of the page need to be updated.
AJAX stands for Asynchronous JavaScript and XML. It is not a new programming language, but a new way to use JavaScript to exchange data between the client side and the server side in a asynchronous fashion. AJAX is based on standards includes XMLHttpRequest object, DOM manipulation with JavaScript, and XML and JSON.
The following are a few commonly used AJAX methods in JQuery. The load method loads data from a server and puts the returned data into the selected element. The AJAX get and post methods with send the requests using the respective HTTP request types.
The following example show the modified version of our TODO list example using AJAx.
Note the client side uses JavaScript code to load the todo list and send the request for adding a new item in the list. The PHP scripts being requests server as the server side by offering a web API. Each PHP script can be viewed a function, which returns data for each parameter combination. The server scripts are as follows:

# Web Services

Concepts and examples: https://www.youtube.com/watch?v=7YcW25PHnAA
Find available web service APIs at http://www.programmableweb.com/

## Testing Tools

Postman - REST client (Chrome app)
apigee.com/console/

# RESTful API

source: http://www.drdobbs.com/web-development/restful-web-services-a-tutorial/240169069
REST stands for Representational State Transfer, which is an architectural style for networked hypermedia applications. A service based on REST is called a RESTful service. RESTful services should have following properties and features:

## Representations

RESTful service provides access to these resources, which must represented using a format such as JSON.

## Messages

The client and service talk to each other via messages. In addition to the message body messages contain metadata such as header - key-value pairs.

## Addressing resources

REST requires each resource to have at least one URI. A RESTful service uses a directory hierarchy like human readable URIs to address its resources. URI should not say anything about the operation or action, which is determined by the HTTP verb.

## Uniform interface

RESTful systems should have a uniform interface. HTTP 1.1 provides a set of methods, called verbs (GET, PUT, POST, DELETE, OPTIONS, HEAD), for this purpose. A Safe HTTP method does not make any changes to the resource on the server. An Idempotent HTTP method has same effect no matter how many times it is performed.

## Stateless

A RESTful service is stateless and does not maintain the application state for any client. A request cannot be dependent on a past request and a service treats each request independently.

## Links between resources

A resource representation can contain links to other resources like an HTML page contains links to other pages.

## Caching

Caching is the concept of storing the generated results and using the stored results instead of generating them repeatedly if the same request arrives in the near future. This can be done on the client, the server, or on any other component between them, such as a proxy server.

## Documenting a RESTful service

A client can simply know the base address of the service and from there it can discover the service on its own by traversing through the resources using links. The method OPTION can be used effectively in the process of discovering a service. Sample documentation of a service can be found at http://www.drdobbs.com/web-development/restful-web-services-a-tutorial/240169069?pgno=3

# Cordova

Apache Cordova is set a APIs for creating native mobile app using only HTML, CSS, and JavaScript.
* Wikibooks: Android/PhoneGap
* Apache Cordova
* Cordova Tutorial

# Node.js

Node.js is a JavaScript framework for building scalable network applications. It provides several modules like:
* npm: a package manager.
* An HTTP server.
* The possibility to manage filesystems, and to create full JS apps.

## Installation
### Windows

Download the .msi on https://nodejs.org/.

### Linux

On Debian, replace the wanted version in the URL. Example for the 14th:

# PHP

CodeIgniter http://www.codeigniter.com/

# Setup a Ubuntu VM with LAMP

* Install VirtualBox
* Install latest Ubuntu server (no GUI) or desktop with Apache/MySQL/PHP
** https://www.digitalocean.com/community/tutorials/how-to-install-linux-apache-mysql-php-lamp-stack-on-ubuntu-14-04
** https://help.ubuntu.com/community/ApacheMySQLPHP
* Optional:
** install guest additions to enable shared clipboard
*** download guest additions iso image: http://download.virtualbox.org/virtualbox/
*** install additions: http://virtualboxes.org/doc/installing-guest-additions-on-ubuntu/
** screen resolution
* Activate user public_html directories: http://kimbriggs.com/computers/computer-notes/linux-notes/apache2-public_html-virtual-directories.file
* Intall and configure phpMyAdmin:
** https://help.ubuntu.com/community/phpMyAdmin
** http://www.liquidweb.com/kb/how-to-install-and-configure-phpmyadmin-on-ubuntu-14-04/