Web Design and Development
Dynamic Website using Javascript and PHP
Some content from:
JavaScript Novice to Ninja
(Darren Jones)
Learning Outcomes
apply HTML, CSS and JavaScript to develop interactive websites
understand enough JavaScript to be able to:
write very simple scripts from scratch
use existing code to augment the functionality of websites
Scratching the surface…
we will just introduce JavaScript in this subject (no time for detailed programming)
basics
examples
inspiration to learn more
main focus / examples
JavaScript for forms – validation
see code files at: https://github.com/lindsaymarkward/JavaScriptExamples
using existing scripts (e.g. image galleries, Facebook integration)
Because it runs in the browser, it's readily available. You don't need to install anything new (unlike Python, Java and others)
4
The DOM is a W3C (World Wide Web Consortium) standard. The DOM defines a standard for accessing documents: "The DOM is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document."
The BOM is the Browser Object Model, which deals with browser components aside from the document, like history, location, navigator and screen (as well as some others that vary by browser).
In the document node is the DOM (Document Object Model), the document object model, which represents the contents of the page. You can manipulate it using javascript.
DOM is a subset of BOM
Because it runs in the browser, it's readily available. You don't need to install anything new (unlike Python, Java and others)
5
Because it runs in the browser, it's readily available. You don't need to install anything new (unlike Python, Java and others)
6
Because it runs in the browser, it's readily available. You don't need to install anything new (unlike Python, Java and others)
7
DOM
BOM
objects
Because it runs in the browser, it's readily available. You don't need to install anything new (unlike Python, Java and others)
8
Because it runs in the browser, it's readily available. You don't need to install anything new (unlike Python, Java and others)
9
How to run JavaScript
in the browser
in the page itself, or
in the JavaScript console (if the browser has one; most do)
You can use console.log(…) to output debugging messages to the console
Online Environments
very useful online test and demo tools:
jsfiddle.net, jsbin.com, codepen.io
e.g. jsfiddle.net/rniemeyer/adNuR
How to include JavaScript in websites
embedded in HTML directly, e.g.
<a id="button" href="#" onclick="alert('Hello World')">Link</a>
function calls in HTML + scripts in same file or linked file <a id="button" href="#" onclick="fn()">Link</a>
unobtrusive - HTML doesn't know anything about JS except to link to it <script src="js/scripts.js"></script>
event
javascript
fn() code must be elsewhere
script tags
Unobtrusive
HTML:
<script src="js/scripts.js”></script>
…
<a id="button" href="#">Link</a>
JavaScript file (scripts.js):
button = document.getElementById('button'); button.addEventListener("click", function() { console.log("Hello World!"); });
Useful commands & functions
alert('Good’); (display messages)
return confirm('Do you want X?’);
(returns true or false)
return prompt('What is your name?');
When you get input, use the return statement to send the value somewhere
All these pop-ups are modal windows which will stop you from doing anything else until you respond
Programming
see SitePoint books/courses if you haven't done much programming before
JavaScript has many syntax and functionality similarities with C and Java including:
variables
if else
for, while and do while loops
switch statements
arrays
functions
some things are quite different and need to be watched out for…
Variables and Types
create variables using the var keyword:
var age = 18;
every variable has a type
JavaScript has six different types of value. there are five primitive data types:
string
number
Boolean
undefined
null
everything else is an object
var length= 16; // Number var lastName= "Johnson"; // String var x {firstName:"John",lastName:"Doe"}; // Object
var x = 16 + 4 + "Volvo"; // 20Volvo
var x = "Volvo" + 16 + 4; // Volvo164
JavaScript evaluates expressions from left to right.
When adding a number and a string, JavaScript will treat the number as a string.
Reserved words
abstract, boolean, break, byte, case, catch, char, class, const, continue, debugger, default, delete, do, double, else, enum, export, extends, false, final, finally, float, for, function, goto, if, implements, import, in, instanceof, int, inteface, long, native, new, null, package, private, protected, public, return, short, static, super, switch, synchronized, this, throw, throws, transient, true, try, typeof, var, volatile, void, while, with
Properties and methods
objects have properties and methods
(primitive types also have these thanks to JavaScript implicitly creating wrapper objects so they appear to be objects)
>> name = "Abraham "
<< "Abraham "
>> typeof name
<< "string"
>> name.length
<< 9
>> name["length"]
<< 9
>> name.trim()
<< "Abraham"
>> Code
<< Output
JS is weakly (not strongly) typed
type coercion is the process of converting the type of a value in the background to try and make an operation work.
"6" * 2 results in 12 (number)
"6" + 2 results in "62" (string)
use type constructors to convert types more safely, e.g.
number("23”)
string(6)
Can you handle the truth?
most values are "truthy"
only seven values are always false and these are known as "falsy" values:
"" // double quoted empty string
'' // single quoted empty string
0
NaN // stands for Not a Number
false
null
undefined
We want equality
== known as "soft equality" uses type coercion
=== known as "hard equality" checks types as well
>> " " == 0 << true >> " " === 0 << false >> " " == "0” << false >> false == "0” << true
Functions
in JavaScript, functions are considered to be just another value
this means that they do all the same tasks that other values and objects can do, such as be assigned to variables, changed and stored in arrays
you can even define a function inside another function
in technical terms, this means that functions are considered to be first-class objects in JavaScript
Creating functions
function literals
function goodbye() { alert("Goodbye World!"); }
function expressions - this assigns an anonymous function to a variable:
var goodbye = function(){ alert("Goodbye World!"); };
in both cases, the function would be called like: goodbye();
DOM – Document Object Model
represents an HTML document as a network of connected nodes that form a tree-like structure
allows you to access elements of a web page and enable interaction with the page
every element is an object that has properties
with JavaScript, you can change anything on the page (without needing to reload it, or actually changing the file, just the browser's view/display of it)
usually you give the elements a unique id and use this in JavaScript to access it
Is HTML the DOM?
https://css-tricks.com/dom/
But the HTML you write is parsed by the browser and turned into the DOM.
25
DOM – Document Object Model
View Source just shows you the HTML that makes up that page. It's probably the exact HTML that you wrote.
It might look like different code if, for example, you work in template files in a backend language and don't look at the compiled HTML output very often. Or there is a "build process" that happens after you write your HTML and the code is put out to the live website. Perhaps that HTML is compressed or otherwise changed.
View Source is a little weird actually. The only people that would care to look at that code are developers and all the major browsers have built in developer tools now. It has probably out-lived its usefulness.
26
DOM – Document Object Model
When you're looking at the panel in whatever DevTools you are using that shows you stuff that looks like HTML, that is a visual representation of the DOM! We made it!
27
DOM – Document Object Model
Well, yeah, it does. It was created directly from your HTML remember. In most simple cases, the visual representation of the DOM will be just like your simple HTML.
But it's often not the same...
28
DOM – Document Object Model
When can the DOM be different than your HTML code?
One possibility: There might are mistakes in your HTML and the browser has fixed them for you.
For instance, lets say you have a <table> element in your HTML and you leave out the required <tbody> element.
The browser will insert that <tbody> for you. It will be there in the DOM, so you'll be able to find it with JavaScript and style it with CSS, even though it's not your HTML!
29
DOM – Document Object Model
Take away from all this:
You write HTML
The browser creates the DOM for that page based on what it "thinks" you really want.
We can use JavaScript to update the DOM to add/remove/edit the original HTML you wrote
This is part of the reason that your HTML may seem correct, but display differently on the page
30
DOM – Document Object Model – Simple view
31
DOM – Document Object Model – Full view
32
Events
every time a user interacts with a Web page, such as clicking on a link, pressing a key, or moving a mouse, an event occurs that JS can detect and respond to.
add events like (old style, mixed-together):
HTML: <a href="#" onclick="fn()">Link</a>
or (newer, unobtrusive = HTML & JS separated):
HTML: <a href="#" id="link">Link</a>
JS: document.getElementById("link"). addEventListener("click", fn);
where fn is an existing function
Example
HTML:
<input type="text" name="email" id="email" onBlur="changeColor(this)" onFocus="changeStyle(this)">
JS:
function changeStyle(element) { element.style.color = "#FF0000"; }
event
function
parameter
HTML attribute
CSS property
JavaScript properties
This is it
this is a special keyword
inside the body of a function, this refers to the object the function is called on
in HTML, this refers to the element where the code is e.g. here this = the input element with id=“email”:
<input type="text" name="email" id="email" onBlur="changeColor(this)" onFocus="changeStyle(this)">
CP1406/CP3568 Examples – Demo
https://github.com/lindsaymarkward/JavaScriptExamples
much of the code in the examples is about manipulating properties based on events
also includes examples of AJAX XMLHttpRequest
Look further into: Start with SitePoint books & courses
JSON – JavaScript Object Notation
AJAX – Asynchronous JavaScript And XML
JQuery and JQueryUI
MongoDB/NoSQL
Libraries/frameworks like:
Node.js, Angular.js, Ember.js, React.js, Knockout, Express, Meteor, famo.us
Some interesting references
https://developer.mozilla.org/en-US/docs/Web/JavaScript
http://shop.oreilly.com/product/9780596517748.do
http://bolinfest.com/javascript/misunderstood.html
Next up: PHP
PHP
The browser requests a page from a webserver via the url
The web server creates the DOM from the HTML submitted
The server also makes any modifications needed due to client-side scripting (JS) and CSS
Then it sends back the entire page
40
PHP
The browser has request a .php page. There are many ways to do this:
Via the url
As the action in a form
As a result of a script
The server finds the PHP script and executes it line by line
The PHP library must be installed on the server to allow PHP to be run
Finally, the server packages the resulting information as HTML for return to the browser
41
Using pre-existing PHP scripts
You have been given two PHP scripts that you can use with your Assessment 2 to handle submitting a form:
welcome.php
This script is used as the action of a form. It expects a name and email address
You can use this script to handle getting registration information from someone (see checkemail.html which uses that script)
upload.php
This script is used as the action of a form. It expects the user to choose a file from their harddrive which is submitted.
The script checks that the file is of appropriate size and type
The test file for this script is uploadForm.html
Show the two scripts and go through them briefly
42
A very simple php script
<html>
<body>
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is:
<?php echo $_POST["email"]; ?>
</body>
</html>
NOTE that we provide the basic HTML tags needed by the browser
The form of a PHP script is: <?php then any commands and ends with ?>
Echo means to print the data to the page
$_POST is where the data is coming from – extracted from the sending form
["name"]; gives us the name of the form element that sent the data If you want to add more fields to your form you will need to add extra code here to get it from POST
Then we close off the page using the </body> and </html> tags
Show the two scripts and go through them briefly
43
Summary
JavaScript can be used to develop interactive websites
you should understand enough JavaScript to be able to:
write very simple scripts from scratch
e.g. form validation
use existing code to augment the functionality of websites
e.g. photo galleries, image sliders…