LIS 390W1A - Lab 14: Introduction to Javascript & PHP

Legend

 
= Javascript
 
= PHP

What is Javascript?

  • Scripting language for controlling the content, presentation, or behavior of a webpage (HTML document, DOM) in the user’s browser.
  • Thus, javascript is a client-side scripting language.

Image depicting how javascript works from a client-server perspective

What is PHP?

  • Scripting language for manipulating content, presentation, and data of webpages on the server.
  • Thus, PHP is a server-side scripting language.

Image depicting how php works from a client-server perspective

PHP and javascript are technically both scripting languages, not programming languages. A scripting language is a language that is compiled during run-time, whereas a programming language is typically compiled before run-time. What this means, is that for both PHP and javascript, the text files that contain the code sit on the server until a webpage is requested. When the webpage is requested, the PHP code is sent to the PHP interpreter, processed, and then sent to the user. When the user's client (web browser) gets the page, the client runs the javascript code though the javascript interpreter. For typical programming languages like C & C++, the code that is written is first compiled into an executable file of some sort (.exe file on windows machines), and then the executable file is run on the computer. This makes running the program much quicker, and is why PHP and javascript are not good languages for complex computation.

What can you do with JavaScript?

  • Manipulate the DOM, e.g.:
    • Create, Remove, and Move nodes
    • Modify styles and other attributes
  • Interact with the user, e.g.:
    • Listen for keyboard + mouse events
    • Process user input
    • Send messages to user
  • Communicate with the server, e.g.:
    • Send and Retrieve data
  • Interact with the browser, e.g.:
    • Detect browser version and settings
    • Firefox extensions are written in JavaScript
  • Reduce the load on the server

Examples:

What can you do with PHP?

  • Create a dynamic page: the same HTTP GET query for a single URL may return pages with different content.
  • Interact with different data storage mechanisms on the server, e.g.:
    • File system: file input, file output, etc.
    • Relational Databases (MYSQL, PostgreSQL, etc.): input and output data
  • Perform serious data processing (quicker).
  • Hide information and/or process.

Examples:

Creating Some Simple Javascript

How do we create JavaScript?

  • The simplest way of incorporating javascript, which can be used anywhere in the HTML document where you can place an element is:

    <script type="text/javascript">
    /* <![CDATA[ */
    	// Insert javascript here.
    /* ]]> */
    </script>
    		

    (For those with javascript experience who find this form unusual, the justification for this form is covered nicely in the article Javascript and XHTML.)

  • Often javascript defined in a script element is placed in the <head>, especially for function definitions, though there can be good reason to put it in the <body> element, for example if you want it to execute at a particular point in the file.
  • Javascript can also be used inline with other elements
  • In URL’s with javascript: scheme
  • Various event attributes added to elements

Your first JavaScript:

  • Create a new folder somewhere in your I: drive courseweb_html folder called "javascript" (you probably need to connect to the I: drive via WebDAV first).
  • Open TextWrangler and create a new HTML file called "helloworld.html" and save it in your javascript folder.
  • Block out a basic HTML document with a <head> and <body>.
  • Add a <h1> heading in the <body> with some message.
  • Now add the code in red to the document, so that it looks something like this:

    <html>
    	<head>
    		<title>Hello world!</title>
    	</head>
    	<body>
    		<h1>Hello Wonderful World</h1>
    		
    <script type="text/javascript"> /* <![CDATA[ */ alert("Hello World"); /* ]]> */ </script>
    </body> </html>

Your second JavaScript:

  • Move the <script> element into the <head>
  • Save the file and Refresh your browser
  • What happened?
  • The browser interprets the HTML sequentially.
  • The Javascript executes before the body has been parsed, so the <h1> headline hasn't been displayed yet.

Some cooler JavaScript:

  • Save your file with a different name, "domexample.html" and close "helloworld.html"
  • Popups are annoying, so let's write our message dynamically into the webpage
  • Delete the <h1> headline
  • Move the <script> element back into the body
  • Now edit the script element so that it contents are replaced by the text in red:

    <html>
    	<head>
    		<title>Hello world!</title>
    	</head>
    	<body>
    		<script type="text/javascript">
    		/* <![CDATA[ */
    		
    var hello = document.createElement("h1"); var msg = document.createTextNode("Hello World"); hello.appendChild(msg); document.body.appendChild(hello);
    /* ]]> */ </script> </body> </html>

Helloworld Autopsy:

  • Let’s read this from right to left:

    var hello = document.createElement("h1");
    1. Create a new element of type "h1"
    2. Store that new element in a variable named hello
  • Now this one, from right to left again:

    var msg = document.createTextNode("Hello World");
    1. Create a new text node with value "Hello World"
    2. Store that new text node in a variable named msg
  • Again:

    hello.appendChild(msg);
    1. Add (append) the text node (stored in variable msg) to the h1 node (stored in variable hello) that we created.
  • Finally:

    document.body.appendChild(hello);
    1. Add (append) the h1 node (stored in variable hello) to the body of the document.

General Concepts

Let us pause for a minute, and note some general concepts which apply to both javascript and php:

  • Variables:
    • document (predefined)
    • hello (we defined it with var)
    • msg (we defined it with var)
  • Strings:
    • "h1"
    • "Hello World"
  • Functions:
    • createElement
    • createTextNode
    • appendChild

Getting (Slightly) More Advanced with JavaScript

Let's now see what functions and accessing javascript via links looks like.

  • Save your file with a new name "domexample2.html" and close the old one.
  • Move the <script> into the <head>
  • Add a hyperlink in the body

    <a href="#">Say Hello</a>
  • Now add a function definition as follows:

    <html>
    	<head>
    		<title>Hello world!</title>
    
    		<script type="text/javascript">
    		/* <![CDATA[ */
    		
    function sayHello() {
    var hello = document.createElement("h1"); var msg = document.createTextNode("Hello World"); hello.appendChild(msg); document.body.appendChild(hello);
    }
    /* ]]> */ </script> </head> <body> <a href="#" onClick="sayHello()">Say Hello</a> </body> </html>
  • Click the link. What happened?
  • Click the link a bunch of times. What happened?
  • The onClick attribute of the <a> tag allows us to execute some JavaScript every time the link is clicked.
  • When we click on the link, we are calling our sayHello function defined above in the <head>

Creating Some Simple PHP

How do we create PHP?

  • It's very simple, and can be used anywhere in the HTML document:

    <?php /*insert php code here */ ?>
    		
  • However, in order for the php interpreter to process the php you have included in the file, you need to have a file of extension .php

Your first PHP:

  • Create a new folder somewhere in your I: drive courseweb_html folder called "php".
  • Open TextWrangler and create a new php file called "helloworld.php" and save it in your php folder.
  • Block out a basic HTML document with a <head> and <body>.
  • Add a <h1> heading in the <body> with some message.
  • Now add the code in red to the document, so that it looks something like this:

    <html>
    	<head>
    		<title>Hello world!</title>
    	</head>
    	<body>
    		<h1>Hello Wonderful World</h1>
    		
    <?php $tmp = "and I say hello!</p>"; echo "<p>You say goodbye, "; echo $tmp; ?>
    </body> </html>
  • This wasn't all that interesting. However, note that any HTML formatting you want to occur needs to be part of the PHP output. For example, if the <p> element was not included, the page would create a validation error that text cannot appear within the <body> element.
  • Notice that all variables in PHP are preceded by the "$" sign.
  • Also notice that you need to include a space at the end of the first line for the second line not to start immediately after the comma. Try deleting the space to see what happens. The php output text output is by default HTML (you can change the default to be a different MIME type (see the predefined header function for more details), thus whitespace is interpreted by the browser as HTML. Add several spaces in a row to one of the output strings: What happens?
  • After you display your page with the functioning php (using the Internet accessible URL, not the filesystem/WebDAV URL), view source. As you can see, there is no php in the source you are viewing. Why is this? (Hint, review this image, and if you can't figure it out, ask!)

Your second PHP:

  • Edit the file so that the variable is defined in the <head> section, e.g.:

    <html>
    	<head>
    		
    <?php $tmp = "and I say hello!</p>"; ?>
    <title>Hello world!</title> </head> <body> <h1>Hello Wonderful World</h1> <?php echo "<p>You say goodbye,;"; echo $tmp; ?> </body> </html>
  • Save the file and Refresh your browser
  • What happened?
  • Notice how it doesn't matter in which <?php ?> tags a variable (or function) is defined, it is accessible throughout the file. Unlike javascript interpreters, PHP interpreters parse the entire file before executing any statements.

Some cooler PHP:

  • Download phptest.php and phptest.css and put them in the php folder in your I: drive.
  • Insert the following php right below the open <body> tag (insert spot #1):

    		<?php
    			$frm_from = (int)$_POST['from'];
    			
    			if ($frm_from) {
    				$frm_txt = htmlspecialchars($_POST['arbstuff']);
    				echo "\t\t<p>\n";
    				echo "\t\t\tThe text you entered last time:\n";
    				echo "\t\t</p>\n";
    				echo "\t\t<p>\n";
    				echo "\t\t", $frm_txt, "\n";
    				echo "\t\t</p>\n";
    				}
    			else {
    				$frm_txt = "This text is not arbitrary unless you write something here...";
    				}
    		?>
    		
  • Insert the following php in insert spot #2:

    <?php echo $frm_txt; ?>
    		
  • Notice the use of "\t" to create a tab and "\n" to create a new line.
  • Notice in the HTML that I created a variable in the form that does not display (the CSS is styled to display: none; for the class hide).

Submission

To turn in your assignment, please upload each file you created to your I: Drive. Then create a new HTML file in your I: drive that links to each of the files you created, and describe what you learned in this exercise (250-500 words) and email me a link to this file. Hint: it is probably a good idea to directly answer all the questions above if you want full credit.

Grading Criteria

Out of 30 points total.

  • HTML validation for all files (link + successful validation): 10 points
  • CSS validation for all files (link + successful validation): 10 points
  • Writeup: 10 points