Web Programming/Printable version


Web Programming

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

Permission is granted to copy, distribute, and/or modify this document under the terms of the Creative Commons Attribution-ShareAlike 3.0 License.

Web and Web Programming

The Web and the Internet

edit

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

edit

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

edit

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.

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 (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

edit

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

HTML

edit

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:

What is HTML?

edit

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

edit

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

<p></p>

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:

<em> emphasized and<bold>bold-faced</em></bold>

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

edit

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).

Meta Tags

edit

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

edit

HTML5 introduces a number of semantic elements to help search engines or other programs better identify the structure of a web page.


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:

CSS Syntax

edit

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:

selector {
  property: value;
  property: value;
  ...
  property: value;
}

The following example rule selects all paragraph elements and set the text color to red and center align the text in the paragraphs.

p {
     color: red;
     text-align: center;
}

You can see a running example at [1].

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.

...
<head>
  <link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
...

Commonly Used Properties

edit

color

edit

See different way to set font color in this example.

font

edit

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

Style Text

edit

font

edit

position

edit

decoration and transformation

edit

CSS3 shadow

edit

float image

edit

Cascading Rule

edit

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:

  1. rules in the style attribute of a tag
  2. rules in the script elements in the head
  3. rules in an external CSS file
  4. rules inherited to from parent elements
  5. 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

edit

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.

a:hover {
  background-color: red;
}

CSS Pseudo-elements

edit

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.

p:first-line {
    color: #ff0000;
}
p::first-line {
    color: #ff0000;
}

CSS3

edit

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

edit

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

rgba(red%, green%, blue%, opacity-value)
hsl(hue-degrees, saturation%, lightness%)
hsla(hue-degrees, saturation%, lightness%, opacity-value)


Layouts

Objectives:

  • use CSS rules to change the default layout of a page
  • identify the difference between different positioning

Resources:

Box Model

edit

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

edit

align

edit

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

edit

border

edit

background

edit

position

edit

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

edit

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.

Here is an example.

Alignment v.s. Floating v.s. Positioning

edit
  • 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:

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 my_php_code.php

PHP Basic Syntax

edit

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:

<!DOCTYPE html>
<html>
<body>

<h1>My hello world page</h1>

<?php
echo "Hello World!";
?>

</body>
</html>

Please check out the following tutorials on w3schools.com to learn basic PHP syntax:

Examples

edit
<html>
  <head>
    <title>My TODO list</title>
  </head>
<body>
  <ul>
    <?php
      $todos = array("Buy milk", "Buy eggs", "Read a book");
      $todo_count = 3;
      for ($i=0; $i<$todo_count; $i++){
        echo "<li>".$todos[$i]."</li>\n";
      }
    ?>
  </ul>
</body>
</html>

The HTML generate by the previous PHP script is as follows:

<html>
  <head>
    <title>My TODO list</title>
  </head>
<body>
  <ul>
    <li>Buy milk</li>
<li>Buy eggs</li>
<li>Read a book</li>
  </ul>
</body>
</html>

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.

<html>
  <head>
    <title>My TODO list</title>
  </head>
<body>
  <ul>
    <?php
      $todos = array("Buy milk", "Buy eggs", "Read a book");
      $todo_count = 3;
      for ($i=0; $i<$todo_count; $i++){?>
    <li><?=$todos[$i]?></i>
    <?php  }
    ?>
  </ul>
</body>
</html>
<html>
  <head>
    <title>My TODO list</title>
  </head>
<body>
  <ul>
    <?php
      $todos = file("todolist.txt");
      $todo_count = count($todos);
      for ($i=0; $i<$todo_count; $i++){
        echo "<li>".$todos[$i]."</li>";
      }
    ?>
  </ul>
</body>
</html>

PHP String Functions

edit

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:

The explode function allows us to "unpack" a string into a array of substrings. The following code

<?php
  $items = explode(":", "item1:item2:item3");
  print_r($items);
?>

will output

 Array
(
    [0] => item1
    [1] => item2
    [2] => item3
)

You can name the substrings using the list notation. The following code

<?php
  list($a, $b) = explode(":", "item1:item2:item3");
  print "a=".$a."\n";
  print "b=".$b;
?>

will output

a=item1
b=item2

The implode function packs a array of strings into a single string.

PHP Array Functions

edit

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:

PHP Global Variables

edit

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

<?php
  print_r($_SERVER);
?>

will output content similar to

Array ( 
[HTTP_HOST] => 198.209.99.99 
[HTTP_CONNECTION] => keep-alive 
[HTTP_CACHE_CONTROL] => max-age=0 
[HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 
[HTTP_USER_AGENT] => Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.122 Safari/537.36 
[HTTP_ACCEPT_ENCODING] => gzip,deflate,sdch 
[HTTP_ACCEPT_LANGUAGE] => en-US,en;
...

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.

<?php
  print_r($_REQUEST);
?>

The actual output is

Array ( [first_name] => Curious [last_name] => George )

$_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
  $first_name = $_REQUEST["first_name"];
  if (isset($_REQUEST["first_name"])){
    print "first_name=".$first_name;
  }else{
    print "first_name parameter is missing.";
  }

PHP File Functions

edit

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:

The following PHP script reads a poem from a file and outputs it as a ordered list.

<ol>
<?php
  $lines = file("poem.txt");
  foreach ($lines as $line){
?>
    <li><?=$line?></li>
<?php
  }
?>
</ol>

The output will appear as follows in a browser window:

1. All that is gold does not glitter,
2. Not all those who wander are lost;
3. The old that is strong does not wither,
4. Deep roots are not reached by the frost.
5. From the ashes a fire shall be woken,
6. A light from the shadows shall spring;
7. Renewed shall be blade that was broken,
8. The crownless again shall be king.

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.

<?php
  $file_names = glob("words/*.txt");
  print_r($file_names);
?>

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).

Array ( [0] => words/hits.txt [1] => words/words.txt )

The next script takes the paths to the files, reads the file contents, and echoes them back to the caller.

<?php
  $files = glob("words/*.txt");
  foreach ($files as $file){
    $content = file_get_contents($file);
?>
  <h1><?=basename($file)?></h1>
  <?=$content ?>
<?php
}
?>

A sample output of the script is as follows. The basename function returns the path's last component, which is the "bare" file name.

 <h1>hits.txt</h1>
 123
 <h1>words.txt</h1>
 prothalamion	noun	a song in celebration of a marriage
 atrabilious	adjective	given to or marked by melancholy; GLOOMY
 hyacinth	noun	a precious stone of the ancients sometimes held to be the  sapphire; a gem zircon or essonite

PHP Include Statement

edit

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.

<?php include "navigation.php"; ?>


Forms

Resources:

Form Syntax

edit

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:

Example

edit

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

edit

We can use a add.php output an HTML form and ask it to submit user input in the form to add_submit.php.

<!--add.php-->
<form action="add_submit.php">
  <label>TODO:<input type="text" name="todo"/></label>
  <input type="submit" name="send" value="Add"/>
</form>

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.

# add_submit.php
<?php
  $todo = $_GET["todo"];
 
  if (isset($todo) && strlen(trim($todo)) != 0){
    file_put_contents("todolist.txt", $todo."\n", FILE_APPEND);
  }
  include "list.php";
?>
<ul>
<?php
  # list.php
  $todos = file("todolist.txt", FILE_IGNORE_NEW_LINES);
  $count = count($todos);
  for ($i=0; $i<$count; $i++){
?>
    <li><?=$todos[$i]?></li>
<?php
  }
?>
</ul>

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.

<form action="todo.php">
  <label>TODO:<input type="text" name="todo"/></label>
  <input type="submit" name="send" value="Add"/>
</form>
<?php
  $todo = $_GET["todo"];
  
  if (isset($todo) && strlen(trim($todo)) != 0){
    file_put_contents("todolist.txt", $todo."\n", FILE_APPEND);
  }

  include "list.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

edit

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.

<?php
  $line_number = 6;
  if (isset($line_number)){
    $lines = file("todolist.txt");
    array_splice($lines, $line_number, 1);
    file_put_contents("todolist.txt", implode("",$lines));
}
?>

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.

http://host/path/to/delete.php?line_number=3

We will need to revise the list.php file to output the delete links.

   <ul>
      <?php
        $todos = file("todolist.txt", FILE_IGNORE_NEW_LINES);
        $count = count($todos);
        for ($i=0; $i<$count; $i++){
      ?>
          <li>
            <?=$todos[$i]?>
            [<a href="delete.php?line_number=<?=$i?>">delete</a>]
          </li>
      <?php
        }
      ?>
    </ul>

The modified web interface should look as follows:

  The HTML source code looks as follows:

<form action="todo.php">
  <label>TODO:<input type="text" name="todo"/></label>
  <input type="submit" name="send" value="Add"/>
</form>
    <ul>
          <li>
            Buy milk            [<a href="delete.php?line_number=0">delete</a>]
          </li>
          <li>
            Buy eggs            [<a href="delete.php?line_number=1">delete</a>]
          </li>
          <li>
            Go for a run            [<a href="delete.php?line_number=2">delete</a>]
          </li>
          <li>
            Read a book            [<a href="delete.php?line_number=3">delete</a>]
          </li>
          <li>
            Teach a class            [<a href="delete.php?line_number=4">delete</a>]
          </li>
          <li>
            readsleepsleep            [<a href="delete.php?line_number=5">delete</a>]
          </li>
          <li>
            two            [<a href="delete.php?line_number=6">delete</a>]
          </li>
          </ul>

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.

<?php
  $line_number = $_GET["line_number"];
  $lines = file("todolist.txt");
  array_splice($lines, $line_number, 1);
  file_put_contents("todolist.txt", implode("",$lines));

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

edit

It would be nice if we can stay on the same page (todo.php). The following code shows the whole application in one script:

<form action="todo.php">
  <label>TODO:<input type="text" name="todo"/></label>
  <input type="submit" name="send" value="Add"/>
</form>
<?php
  $todo = $_GET["todo"];

  if (isset($todo) && strlen(trim($todo)) != 0){
    file_put_contents("todolist.txt", $todo."\n", FILE_APPEND);
  }

  $line_number = $_GET["line_number"];
  if (isset($line_number)){
    $lines = file("todolist.txt");
    array_splice($lines, $line_number, 1);
    file_put_contents("todolist.txt", implode("",$lines));
  }
?>
<ul>
<?php
  $todos = file("todolist.txt", FILE_IGNORE_NEW_LINES);
  $count = count($todos);
  for ($i=0; $i<$count; $i++){
?>
  <li>
    <?=$todos[$i]?>
    [<a href="todo.php?line_number=<?=$i?>">delete</a>]
  </li>
<?php
  }
?>
</ul>

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

 
Symbol depicting responsive web design.

External Resources

edit


JavaScript

Resources:


 
JavaScript is often seen as a key part of client side web programming.

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

edit

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.

function sayHello(){
    alert("Hello!");
}

sayHello();

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.

<!DOCTYPE html>
<html>
<head>
  <script src="demo.js" type="text/javascript"></script>
</head>
<body>
<button id="say_hello">Say Hello</button>
</body>
</html>

The demo.js file has the following content.

window.onload = function(){
  document.getElementById("say_hello").onclick = sayHello;
};

function sayHello(){
  alert("Hello!");
}

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.

<!DOCTYPE html>
<html>
<body>
<button id="say_hello">Say Hello</button>
<script>
  window.onload = function(){
    document.getElementById("say_hello").onclick = sayHello;
  }

  function sayHello(){
    alert("Hello!");
  }
</script>
</body>
</html>

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.

<!DOCTYPE html>
<html>
<body>
<button id="say_hello">Say Hello</button>
<p id="output"></p>

<script>
  window.onload = function(){
    document.getElementById("say_hello").onclick = sayHello;
  };

  function sayHello(){
    var output = document.getElementById("output");
    output.innerHTML = "Hello";
  }
</script>
</body>
</html>

Events

edit

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.

<!DOCTYPE html>
<html>
<body>

<p id="display">5</p>

<button id="start">Start</button>

<script>
  document.getElementById("start").onclick = 
    function() {
      var seconds = document.getElementById('display').innerHTML;
      setTimeout(timesUp, seconds*1000);
    };
  
  function timesUp(){
    alert('Time is up!');
  }
</script>
</body>
</html>

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.

<!DOCTYPE html>
<html>
<body>

<p id="display"></p>

<button id="start">Start</button>

<script>
  var seconds = 10;
  var timer;

  document.getElementById('display').innerHTML=seconds;
  document.getElementById("start").onclick = 
    function() {
      timer = setInterval(update, 1000); // expires every second
    };
  
  function timesUp(){
    alert('Time is up!');
  }
  
  function update(){
    seconds = seconds - 1;
    document.getElementById('display').innerHTML=seconds;
    if (seconds==0){
      clearInterval(timer);
      timesUp();
    }
  }
</script>
</body>
</html>

We can build a complete stop watch using this idea.

<html>
<head>
  <script src="stopwatch.js" type="text/javascript"></script>
</head>
	
<body>
<span id="mm">00</span>:<span id="ss">00</span>
<br/>
<button id="reset">reset</button>
<button id="start">start</button>

<script>
window.onload = function(){
  document.getElementById("reset").onclick = reset;
  document.getElementById("start").onclick = start;
};

var timer = null;
var minutes = 0;
var seconds = 0;
 
function reset(){
  //alert("reset");
  document.getElementById("ss").innerHTML = "00";
  document.getElementById("mm").innerHTML = "00";
  minutes = 0;
  seconds = 0;
}

function start(){
  timer = setInterval(update, 100);
  document.getElementById("reset").disabled = "disabled";
  document.getElementById("start").innerHTML = "stop";
  document.getElementById("start").onclick = stop;
}

function stop(){
  clearInterval(timer);
  document.getElementById("reset").disabled = "";
  document.getElementById("start").innerHTML = "start";
  document.getElementById("start").onclick = start;
  //alert("stop");
}

function update(){
  seconds++;
  if (seconds > 59){
    seconds = 0;
    minutes++;
  }
  if (seconds < 10){
    document.getElementById("ss").innerHTML = "0"+seconds;
  }else{
    document.getElementById("ss").innerHTML = seconds;
  }
	
  if (minutes < 10){
    document.getElementById("mm").innerHTML = "0"+minutes;
  }else{
    document.getElementById("mm").innerHTML = minutes;
  }
}
</script>
</body>
</html>

jQuery

edit

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

edit

Simple syntax rules can be found at

Common utility methods include

Some interesting constructs include:

$(function () {
  //code here
});

is a shorthand expression for

$(document).ready(function(){
  //code here
});

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.

  (function($){
    //code here
   })(jQuery);

Element Selection

edit

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

edit

jQuery makes DOM manipulation easier by providing a rich set of methods we can use. The following are the main categories of such methods:

The following example generates a new square (div) and added to a parent container when the button is clicked.

<!DOCTYPE html>
<html>
<head>
<style>
#box{
  height: 200px;
  width: 200px;
  border: 1px solid black;
}

.square{
  height: 20px;
  width: 20px;
  background-color: blue;
  float: left;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $('button').click(function(){
    var square = $('<div>').addClass('square');
    $('#box').append(square);
  });
});
</script>
</head>
<body>
<div id="box"></div>
<button id="button">add square</button>
</body>
</html>

CSS Manipulation

edit

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

edit

jQuery is designed to respond to all kinds of events on an HTML page.

Effects

edit

The following effects can be achieved using jQuery:

jQuery UI

edit

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:

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.

<html>
<head>
  <title>Add a TODO</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  <script>
  $(document).ready(function(){
    // load the todo list
    $("#list").load("list.php?delay=10");
    
    $(document).ajaxStart(function() {
      $("#loader").show();
    });
    $(document).ajaxStop(function(){
      $("#loader").hide();
    })

    $("button").click(function(){
      $.get("add_submit.php",
      { 
        todo: $('#todo').val(),
        delay: 10
      },
      function(data, status){
        alert("Data: " + data + "\nStatus: " + status);
        $("#list").empty();
        $("#list").append(data);
      })
    });

  });

</script>
</head>
<body>
<label>TODO:<input type="text" id="todo"/></label>
<button>Add</button><br/>
<img id="loader" width="50px" height="50px" src="ajax_loader.gif"/>
<div id="list"></div>
</body>
</html>

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:

<?php
/* add_submit.php */
$todo = $_REQUEST["todo"];
$delay = $_REQUEST["delay"];

if (!isset($delay)){
  $delay = 0;
}

sleep($delay);

if (strlen(trim($todo)) != 0){ 
  file_put_contents("todolist.txt", $todo."\n", FILE_APPEND);
  $lines = file("todolist.txt");
?>
<li><?=array_pop($lines)?><a href="delete.php?line_number=<?=count($lines)-1?>">[x]</li>
<?php  
}
?>
<ul>
      <?php
           /* list.php */
	    $delay = $_REQUEST['delay'];
        if (!isset($delay)){
          $delay=0;
        }
        sleep($delay);
    	$todos = file("todolist.txt", FILE_IGNORE_NEW_LINES); 
        #print_r( $todos);
        $count = count($todos);
        for ($i=0; $i<$count; $i++){
      ?>
          <li><?=$todos[$i]?>
			[<a href="delete.php?line_number=<?=$i?>">x</a>]</li>
      <?php
        }
      ?>
</ul>


Web Services

Web Services

edit

Concepts and examples: https://www.youtube.com/watch?v=7YcW25PHnAA

Find available web service APIs at http://www.programmableweb.com/

Testing Tools

edit

Postman - REST client (Chrome app)

apigee.com/console/

RESTful API

edit

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

edit

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

Messages

edit

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

edit

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

edit

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

edit

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.

edit

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

Caching

edit

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

edit

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.


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

edit

Windows

edit

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

Linux

edit

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

curl -fsSL https://deb.nodesource.com/setup_14.x | bash -
apt-get install -y nodejs
apt-get install -y npm


Frameworks

CodeIgniter http://www.codeigniter.com/


Development Environment Setup

Setup a Ubuntu VM with LAMP

edit