Intro to Web Programming

This post is so that people can follow along in the talk I gave at my old high school today. If you stumbled to it from across the web, feel free to follow along as well!

The slides can be found here.

~~~~

Things you should download to do some simple web programming:
Good GUI text editors (vim is best, but often can be an impediment to learning quickly):
Notepad++ for PCs
TextWrangler for Macs

Debugging your code:
Firefox
Firebug

I highly recommend Firefox and Firebug to debug code, since they clearly show when things are going wrong. I have personally used TextWrangler, so I can vouch for it, but I don’t know much about Notepad++.

~~~~

When using UNIX, some simple symbols to remember:
/ is the root directory
~ is the home directory (usually located at /home/username)
. is the current directory

Check if Python (the programming language we will use for the server) is installed by opening up Terminal.app and typing

python

You should see something like:

Python 2.6.1 (r261:67515, Dec  6 2008, 16:42:21) 
[GCC 4.0.1 (Apple Computer, Inc. build 5370)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>

This is the Python interpreter. We will get to this soon! If the command seems to not be found, then download Python 2.7+ here. Don’t get Python 3, this is a new release that is not backwards compatible.

Type in quit() to exit the interpreter.

All right, let’s get started. Go to a folder you want to work:

cd ~/Desktop/

Then make a folder for this project:

mkdir firstwebsite

Now, enter this folder:

cd firstwebsite

And make your website:

touch index.html

Let’s also add a scripting file where we store our javascript:

touch index.js

This makes an empty file in ~/Desktop/firstwebsite called index.html. Now open the file in your favorite text editor:

edit index.html

If you are using a PC, then edit may not work for you. You may have to physically go to your desktop and open index.html, or use vim to edit stuff:

vim index.html

We are following the convention that many web servers have where index.html is the home page. touch is usually meant to update the modify date of files, but in this case, we are using it to make the files.

Alright, good so far? Now copy and paste the following HTML into index.html:

<!DOCTYPE html>
<html>
    <head>
		<title>Hello World!</title>
  		<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  		<script src="index.js"></script>
	</head>

    <body>
    <div id="greeting">Hello world!</div>
    </body>
</html>

You’re almost done! Now make your webserver by typing the following into the command line:

python -m SimpleHTTPServer 8000

And go to localhost:8000 on Firefox (with Firebug enabled). You should see “Hello world!” displayed in your browser. Yay! With the help of some modern technologies, you successfully asked for and received your first webpage. Check out the GET request you made in Firebug, and the response it elicited from your python SimpleHTTPServer.

To quit the server, press control+C.
~~~
Now, let’s make a more dynamic website. Do

touch index2.html

And now place the following into the file index2.html:

<!DOCTYPE html>
<html>
    <head>
    	<meta charset="UTF-8">
		<title>Hello World (Dynamic)!</title>
  		<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  		<script src="index.js"></script>
	</head>

    <body>
			<input type="text" name="name" id="name" value="First Last">
			<input type="button" id="name_button" value="Enter">
		<br/>
		<div id="greeting">Hello world!</div>
    </body>
</html>

Now add the following to index.js:

$(function(){
	$("#name_button").click(function(){
		$.post("/",{"name":$("#name").val()})
			.done(function(data)
			{
				$("#greeting").text(data);
			});
	});
})

We finally need a new server to respond to POST requests.
Do

touch server.py

And place in it the following:

import threading
import webbrowser
import BaseHTTPServer
import SimpleHTTPServer
import urlparse

PORT = 8000


class TestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    """The test example handler."""

    def do_POST(self):
        length = int(self.headers.getheader('content-length'))        
        data_string = self.rfile.read(length)
        data_string_dict = dict(urlparse.parse_qsl(data_string))
        try:
            result = "Hello "+data_string_dict["name"]+"!"
        except:
            result = 'error'
        self.wfile.write(result)


def start_server():
    """Start the server."""
    server_address = ("", PORT)
    server = BaseHTTPServer.HTTPServer(server_address, TestHandler)
    server.serve_forever()

if __name__ == "__main__":
    start_server()

Now, run

python server.py

This will replace our SimpleHTTPServer from our last example. Finally, log onto localhost:8000/index2.html. Enter your name, and press the Enter button. Now what you have done is changed the webpage dynamically. This is called AJAX, and is used in just about all modern applications. Gmail, for example uses AJAX on a timer to check its server for new messages.

Now go ahead, change the world! The sky is the limit. Good places to get started are with frameworks, like PHP, Django, or Ruby on Rails. They are a quick way to get a website up and running.