Intro to Javascript - York Universitymbrown/EECS1012/12-PuttingItAllTogether.pdf · Net-centric...
Transcript of Intro to Javascript - York Universitymbrown/EECS1012/12-PuttingItAllTogether.pdf · Net-centric...
EECS1012Net-centric Introduction
to Computing
M.S. Brown, EECS – York University 1
Lecture
"Putting It All Together"and a little bit of AJAX
EECS 1012
Acknowledgements
The contents of these slides may be modified and redistributed, please give appropriate credit.
(Creative Commons) Michael S. Brown, 2017.
HTML
EECS1012
3
HTML
Provides the markup language to
generate the structure and content
of a webpage.
PHP (server-side scripting)
EECS1012
5
PHP
Allowed dynamic
generation of HTML
content.
This could be used
with HTML forms to
generate content
based on data
sent by the user.
JavaScript (client-side scripting)
EECS1012
6
JavaScript
Allowed our pages to be
interactive, without having to
contact the server.
Provided the ability to add
"behavior" to the webpage.
The sweet spot
EECS1012
7
JavaScript
HTML
CSS
PHP
Putting this all together, we create the
best of our web experiences.
Three examples
1. Keeping track of # of visitors (PHP only)
2. Inspirational quotes
1. without AJAX
2. with AJAX
3. Online "to do" list
EECS1012
9
HTML page redirected to PHP
We'd prefer the user to type in an HTML page
instead of a PHP page
We can "redirect" the initial HTML page to our PHP
page
EECS1012
12
HTML Redirect
We can have our initial HTML page redirected to a
PHP version.
EECS1012
13
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title> EECS1012: Lab 1 </title>
<meta http-equiv="refresh" content="0; URL='http://localhost/aboutme.php'">
</head>
<body>
</body>
</html>
aboutme.html
Re-directs to aboutme.php
after waiting 0 seconds
HTML Redirect
EECS1012
14
<meta http-equiv="refresh" content="0;
url='http://localhost/aboutme.php'">
Note that the content attribute has double quotes around the following:
wait_time_in_seconds; url='URL to be redirected to'
Back to our example
Revisit our initial webpage – aboutme.html
EECS1012
15
Our PHP code will
modify this part of
the webpage only.
PHP code added to HTML page
EECS1012
16
… HTML code …
<?php/* First check if file exists, if doesn't exist save "1" to it */if (file_exists("visitorCount.txt") == false){file_put_contents("visitorCount.txt", "1");
}/* retrieve content, add one to it, write it back*/$count = file_get_contents("visitorCount.txt");$count = $count + 1;file_put_contents("visitorCount.txt", $count); /* write back to file */
/* print the visitor's count info */print "<p style=\"text-align: center;\"> " . /* concat this */
"You are visitor $count </p> \n"; /* w/ next line */?></body></html>
What is going on?
EECS1012
17
Client
(browser)Server File
visitorCount.txt
1) HTML page redirected to PHP
2) PHP opens the "visitorCount.txt".
Adds one to the value, writes it
back to the file.
Prints the value from the file,
writes it to the HTML page.
Client requests HTML page.
How this PHP code worked
EECS1012
20
PHP code
<?php
$quotes = file("quotes.txt");
$i = array_rand($quotes);
$output = htmlspecialchars($quotes[$i]);
print "<p> <quote> $output </quote> </p> \n";
?>
Quote1...
Quote2....
Quote3…
Quote….
"quotes.txt"
Opens a "quotes.txt" file as an array.
Selects random an array index.
Converts string using htmlspecialchars(..).
Prints the string to a <p> tag.
Quotes using PHP
EECS1012
21
Client
(browser)Server File
Access PHP file
Open's quote.txt
generates a new HTML
sends it
Random Quote
appears. We page is
refreshed in browser
Quote
If you want another quote, you have to access
the PHP code again.
Problem?
To change the quote, we need to call the PHP file
again (i.e. refresh the webpage)
This will update the entire webpage
Can we somehow pass the data in the "quotes.txt"
to our JavaScript file?
EECS1012
22
We want an interactive quote via JS
EECS1012
23
….Add quotes here.
These change on
their own every
3 seconds.
PHP creates the quote in the HTML
EECS1012
24
<div id="box">
<?php
print "<p>";
print '<button id="next">Next</button><button id="stop">Stop</button>';
print " <quote id=\"quote_footer\"> $output </quote> </p> ";
?>
</div>
Javascript code
EECS1012
25
var timerId = null;
var quoteId = 0;
window.onload = function ()
{
$("next").onclick = nextQuote;
$("stop").onclick = stopTimer;
timerId = setInterval(nextQuote, 3000);
}
…
function nextQuote()
{
$("quote_footer").innerHTML = quotes[quoteId];
quoteId++;
if (quoteId >= quotes.length)
quoteId=0;
}
function stopTimer()
{
clearInterval(timerId);
}
Set up "onclick" events.
Set timer to change to next Quote.
nextQuote changes to new quote in
array quotes[ ];
stopTimer() clears the intervalTimer.
Be nice to
have an array
of all the quotes
on the client side
(i.e. inside JavaScript)
Where do we get the "quotes[]"?
EECS1012
26
function nextQuote()
{
$("quote_footer").innerHTML = quotes[quoteId];
quoteId++;
if (quoteId >= quotes.length)
quoteId=0;
}
function stopTimer()
{
clearInterval(timerId);
}
Variable we use
should contain all the quotes
from the "quotes.txt" file.
But this file is on the server!
Quote1...
Quote2....
Quote3…
Quote….
"quotes.txt"
Ideally, we'd like:
quotes = [ "Quote1", "Quote2", "Quote3", …. , "QuoteLast" ];
Use PHP to modify our JS file!
EECS1012
27
<?php$quotes = file("quotes.txt"); /* open file */$write_to_java = "var quotes=[ "; /* generate JS code */$count = count($quotes); /* an array named "quotes" */for($i=0; $i < $count-1; $i++) /* loop through quotes */{$output = htmlspecialchars(trim($quotes[$i])); /* convert */$write_to_java .= "\"$output\","; /* write to array string */
}$output = htmlspecialchars(trim($quotes[$count-1])); /* last Quote */$write_to_java .= "\"$output\" ];"; /* print with ]; end */
/* open JS "template" file – read whole file in as a string */$JSFile = file_get_contents("quotes_template.js");/* write the variable part to the string using concatenate . operator */$JSFile .= $write_to_java;file_put_contents("quotes.js", $JSFile); /* save the JS file */
?>
What just happened?28
Client
(browser)Server
FileAccess PHP file
(2) PHP file modified the JS
code.
copy quotes_template.js's
content + add the generated
var quotes = ["Quote1",
"Quote2",
"Quote3",
… ];
JS File
JS File
with
array
from
Quote
quotes.txt
quotes_template.js
HTML output
+ updated JS file
(1) There is only one call to the PHP file.
It modifies the JS file as necessary.
aboutme2.php
Client
(browser)
(3) All necessary
data is now
in JS file.
We can
update quote
using JS.
Quote
JS code generated by our PHP
program
EECS1012
29
var quotes=[ ""If you want to achieve greatness stop asking for permission." --
Anonymous",""Things work out best for those who make the best of how things work
out." --John Wooden",""To live a creative life, we must lose our fear of being
wrong." --Anonymous",""If you are not willing to risk the usual you will have to
settle for the ordinary." --Jim Rohn",""Trust because you are willing to accept the
risk, not because it's safe or certain." --Anonymous",""Take up one idea. Make
that one idea your life--think of it, dream of it, live on that idea. Let the brain, muscles,
nerves, every part of your body, be full of that idea, and just leave every other idea alone.
This is the way to success." --Swami Vivekananda",""All our dreams can come
true if we have the courage to pursue them." --Walt Disney",""Good things come
to people who wait, but better things come to those who go out and get them." --
Anonymous",""If you do what you always did, you will get what you always got."
--Anonymous",""Success is walking from failure to failure with no loss of
enthusiasm." --Winston Churchill",""Just when the caterpillar thought the world
was ending, he turned into a butterfly." --Proverb",""Successful entrepreneurs are
givers and not takers of positive energy." --Anonymous",""Whenever you see a
successful person you only see the public glories, never the private sacrifices to reach
them." --Vaibhav Shah" ];
Code generation
This style is known as "code generation"
That is, the PHP program generated new code
This is generally considered bad style, but is fairly
common
This style of code generation is working within the
synchronized mode of web server access
EECS1012
30
Synchronous web access
EECS1012
31
• synchronous: user must wait while new pages load
• the typical communication pattern used in web pages (click, wait, refresh)
In this case "event" is submitting a form, or loading
a page.
Asynchronous access
EECS1012
33
Result is sent to JavaScript.
JS can be used to modify the page.
The key here is "partial page".
JS is used to update the webpage.
Asynchronous JavaScript And XML
AJAX (Asychronous JS and XML)
XML = extensive markup language
This is a method to encode up data
This is also a slightly incorrect term, because AJAX does not
require XML – as we will see.
AJAX
Allows JS to make a request to the server using
XMLHttpRequest
When request returns, an event hanlder is called with
the result
JS can update the webpage based on the resultEECS1012
34
How it works
EECS1012
35
https://www.w3schools.com/xml/ajax_intro.asp
AJAX - for our quotes example
EECS1012
36
var quote = null;
var timerID;
window.onload = function ()
{
$("next").onclick = updateQuote;
$("stop").onclick = stopTimer;
timerId = setInterval(getQuote, 3000);
}
function updateQuote()
{
$("quote_footer").innerHTML = quote;
}
function stopTimer()
{
clearInterval(timerId);
}
function getQuote()
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {
quote = this.responseText;
updateQuote();
}
}
};
xmlhttp.open("GET", "quotes.php", true);
xmlhttp.send();
}
AJAX code
Examining the AJAX Request
EECS1012
37
function getQuote()
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {
quote = this.responseText;
updateQuote();
}
}
};
xmlhttp.open("GET", "quotes.php", true);
xmlhttp.send();
}
Create an "AJAX request"
Define an anonymous function to handle
the result when it comes back.
When the event results, check
status to make sure it worked (see next slide).
Set variable "quote" to the response from
the AJAX call. Call the "updateQuote()"
function.
This opens the connection to the
browser. We send a "GET"
post (like forms). We call the
PHP file "quotes.php".
"true" means this is an asynchronous call. send() sends the
request established in "open".
readyState and status
EECS1012
38
Property Description
onreadystatechange Stores a function (or the name of a function) to be called automatically
each time the readyState property changes. This is the event handler
that processes the result after the rquest has been sent.
readyState Holds the status of the XMLHttpRequest. Changes from 0 to 1-4:
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
status 200: "OK" (everything was fine)
404: Page not found (something went wrong)
See previous slide, we check to make sure the readyState=4 and
status=200.
Example – PHP – quotes.php
EECS1012
39
<?php
$quotes = file("quotes.txt"); /* open file as an array */
$i = array_rand($quotes); /* select random index into array */
$response = htmlspecialchars($quotes[$i]); /*convert to HTML *//*special char encoding */
print $response; /* output response – this will returned to the *//* XMLHttpRequest(); */
?>
This is the PHP code called by our XMLHttpRequest();
Note how it doesn't have any HTML output – only prints out the string directly.
What is happening?
EECS1012
40
Client
(browser)Server
FileAccess PHP file
quotes.txt
HTML output to browser
aboutme2.php
Client
(browser)Server
FileAJAX – access PHP file
quotes.txt
AJAX return to JS
(Does not require
webpage to be refreshed)
quotes.php
JS updates
webpage
when request
returns
JS sends
AJAX request
Quote
Online 'ToDo List'
EECS1012
42
List items are stored
on the server.
When the webpage
loads, we retrieve the
items.
If we delete or add, we
send the info to the server.
todo.html, todo.css, todo.js
Todo HTML and Todo PHP43
Client
(browser)Server
Basic HTML page
with JS code
todo.html
Client
(browser)Server
JS code makes
three types of
AJAX calls:(1) todo.php?getList=true(2) todo.pp?delete=item(3) todo.php?add=item
File
todo.txt
todo.php
PHP application
responses depending
on type of request
HTML code44
<body><div id="myDiv"><h2>My Online ToDo List</h2><p> New item: <input type="text" id="myInput"><button id="addButton">Add</button> </p><ul id="myUL"></ul><p> <span id="messageSpan">Hi</span> </p></div></body>
"myUL"
"messageSpan"
"addButton""myInput"
Multi-purpose PHP code
Our JS code will make the following three calls to
the PHP program:
1. todo.php?getlist=true
2. todo.php?add=item_to_add
3. todo.php?delete=item_to_delete
EECS1012
45
Multi-purpose PHP code46
<?php
/* Get the list */if (isset($_GET["getlist"])) {$content = file("todo.txt");for($i=0; $i < count($content); $i++) {print trim($content[$i]) . "\n";
}}
/* add to list */if (isset($_GET["add"])) {$item_to_add = "{$_GET["add"]}\n";file_put_contents("todo.txt", $item_to_add, FILE_APPEND);print "Item <$item_to_add> added to server";
}…
item1
item2
item3
item4
…
todo.txt
if "getlist" is defined.
Opens the file.
prints out the content
separated by a \n
If "add" is defined.
Appends the item to the
"todo.txt" file.
Multi-purpose PHP code
EECS1012
47/* delete item */if (isset($_GET["delete"])){$item_to_delete = $_GET["delete"];$content = file("todo.txt"); file_put_contents("todo.txt", "");
for($i=0; $i < count($content); $i++) { /* if item found - don't write it to file */if (trim($content[$i]) != $item_to_delete) {file_put_contents("todo.txt", $content[$i],
FILE_APPEND);}
}print "Item deleted on server\n";
}?> item1
item2
item3
item4
…
todo.txt
item1
item2
item4
…
todo.txt
don't
copy item
that is to
be delete
Message returned
to AJAX call.
-if "delete" is defined.
-get "item to delete"
from client.
-open "todo" file.
-delete the contents.
- loop through each item
in the file.
- if the name of the item
is the same as the one to
be delete, don't write it
back to the file.
JS code (several pages)
EECS1012
48
/* onload - set addButton's function */
window.onload = function()
{
$("addButton").onclick = addItem;
getListFromServer(); /* calls server to get List */
}
…
JS code
EECS1012
49
function getListFromServer() /* will call todo.php?getlist=true */
{
var xmlhttp = new XMLHttpRequest(); /* make AJAX request */
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {
var items = this.responseText; /* items is a string with each item */
addItemsFromServer(items); /* separated by a \n */
postMessage("Items loaded from server"); /* posts a message */
}
}
}
xmlhttp.open("GET", "todo.php?getlist=true", true);
xmlhttp.send();
}
..
Perform AJAX call to
get the contents of the list.
PHP will return the items as
one big string separated
by "\n".
JS code
EECS1012
50
function addItemsFromServer(items)
{
/* items is a string passed with each time in the list separated by a \n */
/* items.split is equivalent to PHP explode("\n", $items) */
var itemArray = items.split("\n"); /* splits string into array */
for(var i=0; i < itemArray.length; i++) /* for each item in the array */
{
if (itemArray[i] != "") { /* make sure items isn't empty */
var newLi = document.createElement("li"); /* create new item */
newLi.onclick = clickLi; /* set its click event */
newLi.innerHTML = itemArray[i]; /* add content */
$("myUL").appendChild(newLi); /* append to myUL list */
}
}
}
…
Break the string into
an array of items.
Add each item as an <li>
element to the DOM tree.
JS code
EECS1012
51
function postMessage(msg) /* msg is a string to be posted */
{
$("messageSpan").innerHTML = msg;
/* Set a timeout to clear this message after 5 */
/* use an anonymous function to clear message after 3 seconds */
setTimeout(function () {
var messageSpan = document.getElementById("messageSpan");
$("messageSpan").innerHTML = "";
}, 3000);
}
… Simple message function that display
something in the "messageSpan" . .
and then creates a timer event to
delete the contents after 3 seconds.
JS code
EECS1012
52
function clickLi() { /* will call todo.php?delete=item_to_delete */
var result = confirm("Do you want to delete this item?");
if (result == true)
{
var item = this.innerHTML; /* item_to_delete */
$("myUL").removeChild(this); /* remove from HTML using DOM */
var xmlhttp = new XMLHttpRequest(); /* send PHP a message to delete */
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {
postMessage(this.responseText);
}
}
}
xmlhttp.open("GET", "todo.php?delete=" + item, true);
xmlhttp.send();
}
} …
If an "li" is clicked, we use a pop-up
window to ask if we want to delete
the item.
If so, do an AJAX call to
delete the item.
JS code
EECS1012
53 function addItem() { /* will call todo.php?add=item_to_delete */
{
if ($(myInput).value != "") { /* if value is empty do nothing */
var newLi = document.createElement("li"); /* create item */
newLi.innerHTML = $("myInput").value; /* add content */
newLi.onclick = clickLi; /* add clickEvent */
$("myUL").appendChild(newLi); /* append new element to DOM tree */
var xmlhttp = new XMLHttpRequest(); /* Create AJAX call */
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {
postMessage(this.responseText); /* post message */
}
}
}
xmlhttp.open("GET", "todo.php?add=" + $("myInput").value, true);
xmlhttp.send();
}
}
If "addButton" is clicked.
Add a new item to the list,
call PHP code to add the item.
Recap
Three examples to help see how we can put
everything together
Example #2 shows how to do "code generation"
where we use PHP to modify our JS code
Example #2 and #3 show examples using AJAX
Most of the social network platforms use this style of
asynchronous communication between server and
client
NOTE: AJAX will not be on the final exam or labtest
EECS1012
54