Understanding Web Development: From Static Pages to Dynamic Applications
Static vs. Dynamic Web Pages
A static web page is delivered and stored as web content.
A dynamic web page is generated by a web application on the server, using user input to the server.
Dynamic behavior is provided using JavaScript code embedded in the HTML of a web page or as separate linked files specified in the HTML.
HTML: The Foundation of Web Pages
An HTML document is a text file that tells a web browser how to assemble a web page.
- HTML (Hypertext Markup Language) is the markup language for creating web pages.
- “Hypertext” refers to the way in which web pages are linked together.
- “Markup” means you use HTML to mark up a document with tags.
Web Browsers and Servers
A web browser is a software application for accessing information on the World Wide Web.
A web server is a computer that sits on the World Wide Web and listens for requests from web browsers.
Search Engines and Indexing
A search engine is a software system designed to search for information on the World Wide Web.
- Given a user query, search engines get their information by web crawling from site to site.
- The web crawler checks for a standard filename known as robots.txt, which is optionally attached to a website. Example: http://www.example.com/robots.txt
- Robots.txt is a file used by websites that provides information to a web crawler, specifying which areas of the website should not be processed or scanned.
- If the file doesn’t exist, web crawlers assume the web owner wishes to provide no specific instructions and crawl the entire site.
Indexing means associating words and other definable tokens found on web pages to their domain names.
- Then storing the index in a public database.
- The index helps retrieve information that relates to a user query as quickly as possible.
Document Object Model (DOM)
Understanding the DOM
The DOM treats an HTML document as a tree structure where each tag is an object representing a part of the document.
Using the DOM, a web browser will render an HTML document:
- That is, it will transform a plain text document into an interactive, visual representation on a user’s device.
JavaScript and the DOM
JavaScript can:
- Add, change, and remove all of the HTML elements in the page.
- Change all of the CSS styles in the page.
- React to all existing events in the page.
- Create new events within the page.
JavaScript Fundamentals
Data Types
Data types in JavaScript:
- Number
- String
- Boolean
Variables in JavaScript are weakly-typed, which means a variable can be assigned another type.
Identifiers
An identifier is the name of a variable, function, property, or function argument.
- The first character must be a letter, an underscore (_), or a dollar sign ($).
- All other characters may be letters, underscores, dollar signs, or numbers.
Prompt Function
spec = prompt("Your species?", "human");
var myAge = prompt("How old are you?", "99");
prompt allows a second parameter value, which is the default entry, in case the user just presses the Enter key.
Semicolons
In JavaScript, you can omit the semicolon.
Global vs. Local Variables
Global variables are any variable defined outside a JavaScript function.
Variables declared inside a JavaScript function are destroyed as soon as the function exits.
Multiple Variable Declaration
var message = "hi",
found = false,
age = 29;
Five Data Types in JavaScript
- Undefined
- Null
- Boolean
- Number
- String
There is also one complex data type called Object, which is an unordered list of name-value pairs.
Typeof Operator
To determine what a variable is, we can use the typeof operator (can return “function” also).
Boolean Values
Boolean values are written as true and false, not True and False.
NaN (Not a Number)
NaN (not a number) is returned when an operation intended to return a number has failed (dividing by 0 = NaN).
isNaN Function
isNaN returns true if the variable can be converted to a number (aka parsing, boolean true = 1, false = 0).
parseInt and parseFloat Functions
parseInt works on hexadecimal values also.
parseFloat works on string doubles, aka “22.5”, “3.125e7”, etc.
Strings
Strings can be enclosed in single quotes or double quotes.
.length can be used on strings to find their length.
String Immutability
Strings are immutable in JavaScript.
You must destroy the original string to create a new one with the same name.
To change the string held by a variable, the original string must be destroyed and the variable filled with another string containing a new value, like this:
var lang = "Java";
lang = lang + "Script";
toString Method
toString converts numbers into strings.
Type Coercion
5 - true = 4 because true is one.
5 - "" = 5 because "" is zero.
null is converted to zero.
Equality Operators
We use === and !== in JavaScript.
"55" == 55; // true
"55" === 55; // false, different types
"55" != 55; // false, because of conversion
"55" !== 55; // true, not equal because of different types
Functions
Functions in JavaScript need not specify whether they return a value.
To return a value, you use the return statement.
Function Arguments
A JavaScript function doesn’t care how many arguments are passed in, nor does it care about the data types of those arguments.
Just because you define a function to accept two arguments doesn’t mean you can pass in only two arguments.
Arguments in JavaScript are represented as an array internally.
The array is always passed to the function in a function call.
There is an arguments object that can be accessed while inside a function to retrieve the values of each argument that was passed in.
Creating Objects
Two ways to explicitly create an instance of an Object:
- Using the
newoperator - Object literal notation
(1) var person = new Object();
(2) var person = { name: "Nicholas", age: 29 };
JavaScript object properties can also be functions.
Creating Arrays
Two ways to create an array in JavaScript:
var colors = new Array();->var colors = new Array(20);var colors = new Array("red", "blue", "green");- Using array literal notation
var names = []; // creates an empty array
alert(colors.length); // 3
alert(names.length); // 0
alert(colors[0].length);
Exception Handling
Use try...catch for exception handling.
String Methods
string.charAt(pos);
string.charCodeAt(pos);
string.indexOf(searchString, position);
text.lastIndexOf('ss');
string.replace(searchValue, replaceValue);
string.split(separator, limit);
substr(start, length);
Array Methods
We can add a new member to the end of the list (array) using the keyword push:
array.push("new str");
array.length
Splitting Strings
var someString = "The quick brown fox jumped";
var wordArray = someString.split(" "); will split the string into its words, one word per cell:
wordArray[0] = "The";
wordArray[1] = "quick";
DOM Manipulation
Reading Text Input
var cusName = document.getElementById("txtName").value;
Reading a Radio Button
<label><input type="radio" id="radDemo1" name="radDemo" />Radio option 1</label>
if (document.getElementById("radDemo1").value === true) { alert("This radio button is checked!"); }
Writing Output to a Div
<div id="divOutput"></div>
var someText = "The quick brown fox";
document.getElementById("divOutput").innerHTML = someText;
HTML Elements
- Text Boxes:
<input type="text" id="txtBox" value="Hello Jimbo" />Text boxes allow us to enter textual data into a single-line box. - Links:
<a id="lnkExternal" href="https://www.fanshawec.ca/">This is a link to Fanshawe</a> - Images:
<img id="pics" src="pictures/tulip.jpg" /> - Buttons:
<input type="button" id="btnSubmit" value="Submit" /> - Divs:
<div id="divContainer">Some Text</div>
Objects in JavaScript
Object Properties
The simple types of JavaScript are numbers, strings, booleans, null, and undefined.
All other values are objects, including functions, arrays, and regular expressions.
An object is a container of properties, where a property has a name and a value.
Object References
Objects are passed around by reference; they are never copied.
Methods
JavaScript object properties can also be functions – these are called methods.
Constructor Pattern
function PersonType(name, age, job) { this.name = name; this.age = age; this.job = job; }
var person1 = new PersonType("Jimbo", 29, "Teacher");
var person2 = new PersonType("Greg", 27, "Doctor");
Date Objects
var myDate = new Date();
var year = myDate.getFullYear();
var month = myDate.getMonth();
var dayOfMonth = myDate.getDate();
setTimeout Function
setTimeout(function, milliseconds) Executes a function, after waiting a specified number of milliseconds.
JSON (JavaScript Object Notation)
Stringifying Objects
When sending data to a web server, the data has to be a string. Convert a JavaScript object into a string with JSON.stringify(object).
The JSON.stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
Converting Between JavaScript and JSON
Converting from JavaScript objects to JSON and JSON strings back to JavaScript objects:
- JavaScript to JSON:
var stoogeJSON = JSON.stringify(stooge);// assumingstoogeis a JavaScript object - JSON to JavaScript:
var stooge = JSON.parse(stoogeJSON);
AJAX (Asynchronous JavaScript and XML)
Asynchronous Operations
What is asynchronous?
During the period of time between the sending of the request and the response being returned, the browser (and the user) are free to continue working; i.e., no wait.
