Class 8 – In-class-assignment

July 27th, 2010 § 0

This assignment is meant to give practice to the most important parts of PHP besides database integration, which is addressed in separate assignments.  The core concepts are include files and passing data (a.k.a. persistent data) using forms, links, and cookies.

Your assignment is to make a site consisting of four web pages:

  • Home (index.php)
  • News (news.php)
  • Contact Us (contact.php)
  • Thank You (thank_you.php)

There will also be multiple other files that the user never sees directly.  These will be:

  • process_name.php (process the data the user enters on the Home page)
  • process_contact.php (process the data the user enters on the Contact Us page)
  • _article1.php, _article2.php, _article3.php, etc (the XHTML snippets for each article linked to from the News page)

Home (index.php)

Home page

Home page

Global navigation.  The Home page, like every other page on the site, has a top navigation menu with links to Home, News, and Contact.  This menu should use the technique of creating horizontal menus from list tags.  The global navigation should be created as a separate file so it can be included on all other pages of the site in a templatized manner.

Form.  The Home page also has a form the user can fill in with their first and last names.  This form should submit the data the user enters to a script file called process_name.php via the HTTP POST method, which does something with that data.

The code for the form will probably look something like the following. Note the action and method attributes of the form tag and the name attributes of the two form input elements. These are all important and you must understand why they are there:

<form action="process_name.php" method="POST">
	<label for="first_name">First Name:</label>
	<input type="text" id="first_name" name="first_name" />
	<br />
	<label for="last_name">Last Name:</label>
	<input type="text" id="last_name" name="last_name" />
	<br />
	<input type="submit" value="Enter site!" />
</form>

process_name.php

When the user clicks the submit button on the form on the Home page, the data they entered is sent along with the HTTP POST request for the file, process_name.php.

process_name.php should take the first name that the user entered in the form and store it semi-permanently in a cookie. Setting a cookie is handled by PHP’s built-in setcookie() function.

Once that is done setting the cookie, this script should redirect the user to the News page (news.php).  Redirecting is done using PHP’s built-in header() function, which allows you to send customized HTTP headers from the server to the client.

News (news.php)

News page

News page

Global navigation.  The News page, like the Home page, includes the global top navigation from the external file.

Reading the cookie.  The News page also reads the cookie which has the user’s first name in it.  To read a cookie, you can use PHP’s built-in $_COOKIE associative array.

News articles.  Each article title in the list of articles titles on the left side of the News page should be a link to news.php.  Along with each link, we will be passing the id of the article the user clicked on using the technique of passing data via links.

The XHTML for the article links will look something like the following.  Notice how each link passes a different article_id parameter in the query string:

<ul>
	<li><a href="news.php?article_id=1">article title 1</a></li>
	<li><a href="news.php?article_id=2">article title 2</a></li>
	<li><a href="news.php?article_id=3">article title 3</a></li>
</ul>

Loading the correct article.  The News page is therefore a template that can be used to load up any article, depending which link is clicked.  So, obviously, the code must somehow determine which article to load up.

In the code from the example linked above,  you’ll see that we find out which article link was clicked by the user by looking for the article_id parameter that was submitted along with the request for the news.php page in the query string in each link.

$articleId = $_REQUEST['article_id']; //get the article id from the browser's request data

//check to make sure there is an article id that was requested
//is_numeric() is a built-in PHP function that checks to make sure a variable is a number
//the ! is a logical NOT, so this statement says "if the article id is NOT a number, do the following:"
if (!is_numeric($articleId)) {
	//if there was no article id requested, use the number 1 as a default
	$articleId = 1;
}

Then, depending on which article id was requested, in the body of the XHTML document on the news.php page, we load up a different include file with the correct article content in it.

//load up the article that was requested from the external article content files
if ($articleId == 1) {
	//include an external XHTML snippet into this template
	include("_article1.html");
}
elseif ($articleId == 2) {
	include("_article2.html");
}
elseif ($articleId == 3) {
	include("_article3.html");
}
//...and so on for all the other articles

Contact Us (contact.php)

Contact Us page

Contact Us page

Global navigation.   The Contact Us page includes the global navigation the same way as the other pages.

Article links.  It also has the set of article links on the left side of the page, the same as on the News page.  These should each link to news.php and pass along their corresponding article_id parameters, exactly as described for the News page.

Contact form.  The form allows the user to send an email to the site administrators.  When a user fills out the form and clicks submit, the form sends a request for the script, process_contact.php, which handles sending the email.

process_contact.php

process_contact.php, like process_name.php, is invisible to the user – the user never sees it directly.  This script takes the data that the user entered into the form on the Contact Us page, and sends it in an email to the site administrators.

Once the email has been sent using PHP’s built-in mail() function, the script then redirects the user to the Thank You page (thank_you.php) using PHP’s built-in header() function, the same way we did it on process_name.php.

Thank You (thank_you.php)

Thank You page

Thank You page

Global navigation.  This page uses the same global navigation links and same article list as seen on the other pages.

Thank you message.  The main content of this page is a message thanking the user for submitting the Contact form.

			<form action="process_name.php" method="POST">
				<label for="first_name">First Name:</label>
				<input type="text" id="first_name" name="first_name" />
				<br />
				<label for="last_name">Last Name:</label>
				<input type="text" id="last_name" name="last_name" />
				<br />
				<input type="submit" value="Enter site!" />
			</form>

Class 12 – Intro to Using a Subversion Client

May 3rd, 2010 § 0

The following is a brief example of working within a Subversion version control setup.  In this case, we will assume that some overworked server administrator (i.e. me)  has set up a repository where a large amount of source code magically is stored and backed up by Subversion, a popular version control system.  In our case, the source code is all the example files from this course.

Read the overview of Subversion concepts in the post linked above before proceeding.

The hypothetical setup

The under appreciated developers (i.e. you), just need a way to checkout (i.e. download) the latest copy of the code from the repository (i.e. the server), make some changes to some of the code, and then commit (i.e. upload) your changes back to the repository.  You do this so that we can track the changes made to the files and so that everyone else can download new-and-improved version of the source code that you created at their leisure.

Using source control keeps the source code safe from being accidentally deleted, prevents two developers from overwriting the same file at the same time, and it keeps a record of who changed what and when they did it so that your manager (i.e. me) can make sure his minions (i.e. you) are doing their assigned jobs in a timely manner.

Think of it as a backup system with benefits.

The Subversion client

To interface with our Subversion repository, we use a Subversion client application.  Just as we use web browser clients to surf web pages on the server, and we use file transfer clients to browse files on the server, we also use Subversion clients to manipulate version-controlled files on the Subversion server.

The popular client applications for Subversion provide nice graphical user interfaces for you to use so you don’t have to manually send Subversion commands to our Subversion repository on the Linux server.  Popular Subversion clients that I currently recommend are TortoiseSVN for the PC and SvnX for the Mac.  Both add extra Subversion-related options to the context menu (right click menu on PC; control-click on the Mac) within Windows Explorer and Mac Finder, respectively.

Make sure you have one of these clients installed before following the instructions below.

Getting a working copy of the code

To get a “working copy” of the code, meaning to download the latest version of all the code from the Subversion server, you make a folder on your client machine where you want to store your copy of the code.

a folder to hold our working copy of the code

a folder to hold our working copy of the code

Right click on the folder name and select “Checkout” from the new options that the Subversion client added to your context menu.

Subversion checkout

Subversion checkout

Enter the URL of the repository: “http://svn.onepotcooking.com/webdev/trunk” and the usual username/password in the screen that pops up.

Checkout settings

Checkout settings

Successfully logging in will checkout (i.e. download)  a full copy of all the latest source code in the repository and put it into the selected folder on your client.  You will see that the folder and files on your computer have special icons next to them indicating their version control status.

Everything's good

Everything's good

The green checkmark icon means that you have not modified any of the files in this folder since last downloading the files from the Subversion server.

You’re now ready to make changes to some code.

Make some changes

Go into the source code you just checked out on your client and open up the file class12/subversion/index.html in your text editor of choice and make some changes to that file.

Update the code

You’re almost ready to “commit” (i.e. upload) your changes back to the repository.  But first you have to make sure nobody else changed the same files as you between the time you last downloaded them from the repository and the time you finished editing them.

If two people edit the same file at the same time, you wouldn’t want one person to overwrite the other’s work.  So Subversion automatically checks for conflicts.  If they are easy to solve, such as if one person edited the top of a file while the other person edited the bottom, Subversion merges the two copies of the file automatically.  If the conflicts are complicated, Subversion will as you to manually merge the two versions of the conflicted file.

So update your working copy with a fresh copy of the latest code from the repository by using the Subversion client’s update command on the project folder.  This will update everything inside of the folder and check for conflicts between the changes you have made and the changes others have made.

Subversion update

Subversion update

Commit your changes

Once any conflicts have been resolved, you are ready to commit your code to the repository.

Use the Subversion client’s commit option to upload your copy of the entire folder to the repository for safe keeping.  You can also just commit specific  files rather than the whole folder, but for now we’ll upload any changes we made to any files in the folder to keep things simpler.  Subversion is smart enough to only upload the files that have been modified anyway.

Subversion commit

Subversion commit

Add a file

Now let’s say you want to add a new file to this project.  On your client computer, create a new file in the class12/subversion folder called <your_name>.html, where <your_name> is replaced with your first name and last initial, of course.

By creating this file on your client machine, it is not yet added into the version control system unless you make it so.  To add it to the Subversion repository, you need to use the Subversion “add” command.  So right-click on the file and click the Subversion add command.

Subversion add

Subversion add

Adding a new file is just like making any other change, whether it be adding, deleting, or modifying a file on your client.  The changes you make on your client are not uploaded to the server repository until you commit them using Subversion’s commit command.

So now go ahead and commit the changes you’ve made.

Subversion commit

Subversion commit

The next time anyone else updates their “working copy” of the code using the Subversion update command, they will see this new file has been added.  In other words, if I don’t see your file the next time I update, I will know you didn’t follow this tutorial!  I should have forced you to use this technology from the beginning of this course.

Further changes

From this point onward, always download the latest copy of all files using Subversion’s update command on the project folder before you make major changes.  This reduces the chance that your work will have a conflict with another developer’s work, and it will reduce any chance that you are working on an outdated copy of a file.

Class 11 – Intro to Privacy on the Web

May 1st, 2010 § 0

Despite a very vocal minority of concerned citizens, privacy does not seem to be anywhere near as big an issue in the news as it could potentially be.

You should assume that just about everything you do online can be tracked and traced, if someone were to put the effort into doing so.  And some people are putting in that effort.

Children’s Privacy & COPPA Compliance

A topic that has received some attention is children’s privacy.  The Children’s Online Privacy Protection Act of 1998 (COPPA) defines a set of compliance guidelines for sites that collect personal information from children under the age of 13.

The act itself is a short read.  In summary, it declares that websites dealing with children’s information must do their best to obtain parental consent before storing any personally identifiable information or communicating directly to children.  Parents of children must also be allowed to request a copy of all the information the site has stored about their children and request that the data be deleted and no further data be collected on their children.  The website must disclose how they are using that information, whether they are using it for direct marketing, prize giving in competitions, providing it to third parties, etc.

In practice, parental consent is often obtained by putting a checkbox on the page that could easily be clicked by someone other than the parent.  Sometimes, the parent’s email address is required in order to register with the site – an email sent to the parent with a link to approve the collection of information about their children.  In general, the burden falls on the website operator to do their best to be compliant with COPPA.  Each site, if it runs into legal problems, is evaluated on a case-by-case basis.

Network Eavesdropping

Like all telecommunications, the Internet holds a risk that your communication will be intercepted while en route between you and the intended counter-party, and the data that you assumed was private will be picked up by a third party, be that the government, a hacker, a neighbor, or an employer.

When you visit a website, the data packets that constitute your client request and the server’s response pass through a variety of network nodes on the way to get to their intended destination.

Wi-fi vs. Wired

The first vector of transmission in a typical home or office setup may be between your computer and a router.  If you are using a wireless router, your radio transmitter is broadcasting data to anyone within your router’s transmission radius, which can be quite large.  Even if you are using an encrypted connection to your wireless router, such as WEP or WPA, a hacker with very little skill will be able to crack your encryption system using free software readily availble online (AirSnort, AirCrack, WEPCrack, Ethereal, etc).

With a wired connection to a router, the hacker would have to have access to tap into the actual wires involved in your connection, which reduces the risk significantly.

Your Employer

If you use the Internet at work, your employer has legal right to view emails you send using their email system.  They also have the right to track which websites you visit using their network.  Your employer may or may not choose to exercise that right.

Your employer no doubt knows your identity, so they are able to link your Intenet usage to your personal identity without problem.

Your Internet Service Provider

At home or at work, you probably pay an Internet Service Provider (ISP) to provide you with Internet service.  When you stop paying for service, they cut it off.  When you profusely download illegal copies of movies, your ISP may send you a warning that you must stop doing so or face the legal consequences.

They are able to do all this because all your internet traffic goes through network nodes controlled by the ISP.  They are the gateway through which all your internet data passes. And the network connection your computer uses has a unique identifier called an IP address, so they know it’s you and not someone else. The ISP may be (and undoubtedly is to some extent) analyzing your Internet usage.

In order to sign up for service, you have supplied your name, address, phone number, credit card number, and other personally identifiable information to your ISP in order to set up your account.  So they are able to tie your IP address and thus your Internet usage to your identity without difficulty.

Your IP address is not just seen by your ISP.  Your unique IP address is supplied as a header along with every HTTP request you make on the web.  It is standard operating procedure for most sites to log IP addresses of their visitors.

Email

When you send an email, your email program and the recipient’s email program both have copies of that email.  If you are both using email programs on your own computers, and the email does not pass through a webmail service, then the main risk to your privacy involves potential interception of that email while it is in transit between your computer and the recipient’s computer.

If, however, either you or the recipient uses a webmail system, those copies of your email reside on servers owned and operated by some other entity, such as Google, Yahoo, a university, and employer, etc.  So your email is only as private as the poorest privacy policy of either your or the recipient’s email service provider.

Search & Single sign-on

If you use webmail services provided by companies that additionally offer other services, such as search or other online services, logging in to your webmail account also logs you in to the other services.  So if you search, as a logged in user, your search queries are being tied to your email address, which are most likely tied to other aspects of your online and personal identities.

For example, if you use Gmail, your email account and the contents of all the emails inside of it are tied to the blogs you read in your Google Reader Account, all Google searches you’ve done while logged in (and probably some while logged out), and any other behavior or usage you perform with any other Google service, such as Google Maps, Google Wave, Blogger, Youtube, the ads you click on that are operated by Doubleclick, the content of any websites you operate that use Google Analytics to track usage or Google AdSense to server advertising, etc.  Google has such a reach across the web due to its advertising that most likely they have a large data set about your behavior online.

If you’re wondering whether Google is obligated to keep any of this information private and to remove your personally identifiable information if they choose to analyze it, you should probably read their Privacy Policy.

Privacy Policies, as you probably have experienced, change frequently.  What is written there today may be gone tomorrow.  We have all received mail from our banks indicating changes to our policies.  Social networks, webmail applications, and other online services do the same.  As their business and legal needs change, so do their Privacy Policies.  You may receive a letter in the mail indicating this, or a screen that pops up on their website, or some more subtle indicator that something has changed.  Usually, you implicitly agree to their new terms by either clicking a button or closing the window.

So just because a site promises to keep your data private today doesn’t mean that it will always be so.  How vigilant you want to be about these policies is up to you, obviously.

Social networking

It goes without saying that social networking sites collect personally identifiable data.  That is their primary business.  All actions you take on any major social networking site, such as Facebook, MySpace, LinkedIn, Twitter, and others are logged for later analysis.  Whether or not these sites are obligated to maintain the privacy of these records is of course regulated by their Terms of Service and Privacy Policies, which almost nobody reads.

Facebook, in particular, has a strong advertising revenue model.  Like a mini-Google, they target ads directly to the individual viewer so the viewer is more likely to find any given ad relevant and click it.  This is done by profiling users, analyzing their likes and dislikes, and predicting what sorts of products and services they may be interested in.

Like other ad-based online services, they collect as much behavioral data as possible.  It is not especially paranoid to assume that they could be analyzing all links posted to profiles, the content of all emails sent between users, all posts that a user has clicked to indicate they “Like” it, and all behavior gathered from third-party sites that integrate the Facebook API and the Facebook Social Plugins.

Facebook has just launched a major push to integrate its social networking features on third-party sites across the web.  Actually, this is mostly just a repackaging of something they have been doing for a while now. As Facebook content is integrated into more of third-party sites, Facebook will have more data to tie to personal accounts and analyze for potential revenue streams.

Of course, sites like Facebook are wary of breaching the trust of their users.  If users distrust the site, they will no longer use it.  For this reason, if none other, they are unlikely to expose most of the data they collect.  However, who knows how they will operate in the future.  Again, it depends on the Privacy Policy and Terms of Service legalese that nobody reads.

If and when any of these sites begin to decline in popularity, and the users start to leave anyway, social networking sites will perhaps look for ways to monetize on the information they have stored about user behavior and tendencies.  Perhaps this will include personally identifiable information, perhaps not…. better read that Privacy Policy.

References & other links

Class 11 – HTTP Basic Authentication using .htaccess files

April 27th, 2010 § 0

Overview

HTTP is the protocol which web browsers and web servers use to communicate via client requests and server responses, respectively.  We’ve seen that the browser uses HTTP GET and POST methods to request data from the server.

HTTP also provides a very basic level of authentication which you can use to password-protect your sites or certain folders within your sites.  And Apache servers, such as our class server, make it is possible to use this authentication system by simply writing a bit of special code in a file called .htaccess.

We have previously used .htaccess files for rewriting URLs to create Fancy URLs.  The .htaccess file is a directory-specific configuration file – it can hold a variety of server settings that apply only to the folder in which you place it.  This post is about one such setting.

Password-protecting a folder

To password protect a specific folder, we will create two files: one named .htaccess and another named .htpasswd.

.htaccess holds the server instructions indicating that the folder should be password protected.  This file gets placed in the folder which you want to password protect.

.htpasswd holds the username/password combinations of users who are allowed to view the folder.  Passwords are encrypted.  This gets placed somewhere on the server where it is not accessible from the web – you don’t want people loading this file up directly in their web browsers.

The .htaccess file

The .htaccess file contains the following code.

AuthUserFile <the server path to the folder where your .htpasswd file will live>/.htpasswd
AuthGroupFile /dev/null
AuthName EnterPassword
AuthType Basic

Replace <the server path to the folder where your .htpasswd file will live> with the path to your own .htpasswd file.  Ideally this will be somewhere outside of the web root of the server.  On the class server, the web root is the folder /home/scps/onepotcooking.com/

As an aside, saying this is the “web root” means that when a user goes to http://onepotcooking.com in their browser, they will by default view the files in the folder /home/scps/onepotcooking.com.  The “server root” is /, the very topmost folder on the server.

So, if your name is George Washington, perhaps put your .htpasswd file at

/home/scps/passwords/georgewashington/.htpasswd

so it is outside of the web root, yet still somewhere you might be able to find it again if you ever went looking.

The .htpasswd file

The .htpasswd file will contain one of the following lines for each user that has access to the protected folder:

<username>:<encrypted password>

Replace <username> with the username of the user you want to give access.  And replace <encrypted password> with an encrypted password for that user.

How do you get an encrypted password?  You use one of the many websites that encrypt your .htpasswd passwords for you for free, such as this one.

So, for example, if your username is “scps” and your encrypted password is “pnzpsMNdWW6aw”, you will put the following line in your .htpasswd file:

scps:pnzpsMNdWW6aw

And you will save this .htpasswd file into the folder that you indicated in the first line of your .htaccess file.

An example

See an example here.  The username is our standard username, and the password is our standard password minus the last character.  You’ll notice that I have been naughty and put the .htpasswd file in the same folder as the .htaccess file.  On a real site you shouldn’t put it anywhere where a web browser can find it.

How it works

Here’s an overview of the steps that are happening behind the scenes to make this system work:

  1. Your client (most likely your web browser) makes a standard HTTP GET request for a password protected area of the server
  2. The server looks for any .htaccess file in the requested folder
  3. The server reads the .htaccess file and sees that the requested file or folder should be password protected
  4. The server responds to the client with an HTTP HTTP response code indicating that the requested file is password protected.
  5. The browser is built to know what to do with this response code: it pops up a dialog that the user must fill in with a username and password
  6. The user fills in the username and password and clicks submit
  7. The client sends another HTTP GET request to the server, but this time includes the login credentials as extra HTTP headers along with the request.
  8. The server again looks at the .htaccess file and sees that the requested file or folder is password protected, but this time notices that the client included the necessary login credentials along with the request
  9. The server responds to the client with the requested page
  10. The client stores the login credentials the user entered somewhere on the client machine (similar to a cookie) so that next time the page is requested, it doesn’t have to ask the user to enter them again.  The client just sends them to the server in the HTTP headers automatically.

Class 11 – Examples of Popular CMS’s

April 25th, 2010 § 0

The following CMSs are up and running on our class server.  Most of these CMS installations have two distinct web interfaces: one for “end-users”, meaning the website the public sees; and another interface for administrators to manage the content that is displayed on the public site.

Each of these CMS’s can be skinned (a.k.a. themed) to look the way you want them to.  I have set them up to use the default styles for starters. For the popular CMS’s, you can often find themes that other designers have made that you can easily use on your own site.

However, if you want to create your own custom theme, rather than using someone else’s, you often will have to spend a good deal of time learning the intricacies of skinning the particular type of cat you have adopted.

These examples are yours.  Feel free to play around with them, modify them, etc.

Drupal

Drupal is one of the most popular open-source general-purpose CMS’s.

Joomla

Joomla is one the most popular open-source general-purpose CMS’s.

WordPress

WordPress was originally created as a CMS specifically for blogs.  But it has since added features that make it, at this point, a very popular general-purpose CMS.

ZenCart

ZenCart is a CMS designed specifically for e-commerce sites.  It provides easy setup of a storefront, shopping cart, and integration with popular payment processing gateways.

Moodle

Moodle is a CMS designed specifically for online learning (e-learning)  sites.

MediaWiki

MediaWiki is one example of a wiki platform.  It was originally developed as the platform behind Wikipedia, but is now its own product that can be used by independent site operators.

phpBB

phpBB is a popular message board CMS

Indexhibit

Indexhibit is a truly bare-bones CMS that does nothing fancy, but is very easy to use.

ZenPhoto

ZenPhoto is a CMS designed specifically for photo gallery sites.

Class 10 – Intro to AJAX

April 22nd, 2010 § 0

AJAX is an acronym that stands for Asynchronous Javascript And XML.  It refers to a specific feature of the browsers’ implementations of Javascript that became popular in the first few years of this century because it provided a way in which web pages could load content on demand in reaction to a user’s actions, rather than preloading all content with the initial page load, as had been the norm previously.

Many people in the web industry conflate the terms AJAX and dHTML.  Since you are taking this class, you should know the accurate meaning of each of these terms, even if you choose not to stick to the correct meanings when conversing with the ignorant and incorrigible masses.

dHTML

Since Javascript was first introduced into Netscape Navigator in 1995, people have been using it to change the content of web pages.  In other words, long before AJAX was even possible, there was dHTML.  Dynamic HTML is the technique, which we have already seen, of using Javascript to change the content of the page dynamically.  Most typically, this change is in response to a user’s action, such as a click, a mouseover, mouseout, or some other action that changes the appearance of the page in some way.  Often, these changes are simply showing and hiding various parts of the content, or changing the styles associated with some of the content.

By preparing Javascript, CSS, and XHTML in just the right way, a website maker can make a page seem to be dynamic and responsive to user actions.  dHTML refers to this use of Javascript, in combination with CSS and XHTML, to make a page seem dynamic and responsive.

People don’t use the term dHTML very much anymore, although the dHTML techniques are used more than ever.

AJAX

AJAX refers exclusively to the technique in Javascript whereby Javascript code on a page makes a request to the server without requiring a reload of the entire web page.  As we have discussed the client/server relationship, the HTTP GET and HTTP POST methods, persistent data and passing data, we have spoken as if a request to the server is one and the same as the loading a whole web page in the browser.  Now you know that there is a way to make requests to the server without requiring the reload of the entire page – it is called AJAX.

After an AJAX request is made from the Javascript code running on the client to the server, the server may respond, as it usually does to any request.  The Javascript code that made the request often waits [asynchronously] for that response.  Once the response is received from the server, the Javascript code on the client then updates the content of the page dynamically using standard dHTML techniques depending on exactly what response it got back.

People often [inacurrately] use the term AJAX to mean any dHTML, regardless of whether it actually involves a request to the server.  The term, AJAX, has been usurped by marketers to indicate any kind of dynamic content.

Conceptually, making an AJAX request is identical to any other request to the web server.  The Javascript code makes the request using either HTTP GET or HTTP POST.  The client can pass data to the server along with that request, or not.  The server can process that request using PHP or some other server-side language, read any data that was passed, do some business logic, and respond appropriately.

According to how AJAX was originally conceived, the server was supposed to respond with some XML code that the browser thean parsed.  Practically-speaking, the browser is not especially good at parsing XML, so receiving a response in XML is more work than it’s worth.  Today, having the server respond with XML is the exception rather than the rule, although it is still done.  However, these days the server is programmed to usually respond either with an XHTML snippet which is then dynamically output on the page by the Javascript script on the client, or the server responds with a Javascript code snippet of its own which is then run by the client.

JQuery

Naturally, Internet Explorer handles making AJAX requests differently from Firefox and the other popular browsers.  Once again, JQuery solves this problem by providing a set of functions that normalize the browser differences for us.  While you can, of course, use the native Javascript AJAX methods to handle the asynchronous requests to the server, I strongly recommend that you use JQuery or another Javascript framework instead to make your code more reliable across browsers, and to keep it simpler and easier to maintain.

Class 8 – A simple CMS for SQL CRUD

April 18th, 2010 § 0

Working off of the example code from the Basic SQL example files, here is a slightly more sophisticated set of pages that when used together, create a sort of Content Management System for our animals application.

How it works

Here is a user flow diagram outlining how this application fits together.  Below the diagram is an overview of each step.

User flow diagram for Basic SQL CMS

User flow diagram for Basic SQL CMS

read.php

In this version of the files, the pages that handle each of the CRUD commands are all linked together.  A user can view the animals stored in the database on the main page, read.php. Read.php simply queries the database for a list of all the rows stored in the animals table, and outputs each of those rows into the XHTML for the page.

The user can click links to “update” or “delete” any individual animal.  When they click either of those links, the id of the selected animal is passed in the query string of the link to the corresponding page, either update.php or delete.php.

update.php

Update.php displays a form that the user can use to change the name of the animal that was clicked.  The first time this page is loaded, this form is prepopulated with the existing name of the animal that was clicked, which has been retrieved from the database.

The id of the animal and its new name are passed along with another request for update.php once the user clicks the submit button.  Update.php this time updates the selected row in the animals table and redirects the user back to read.php, where the user can see the updated list of names.

delete.php

Delete.php simply runs a query that deletes the selected row from the database, and then redirects the user to read.php, where they can see the updated list of animals.

create.php

A user can click a link to “add a new animal” on read.php.  This takes them to create.php, where they can enter a new animal name into a form.  When they submit the form, the animal name is passed along with another request for create.php.

Create.php this time creates a new row in the database table for the new animal, and then redirects the user to read.php, where they can see the updated list of animals.

Class 7 – The XML declaration in your XHTML code can cause problems if your server has PHP short tags enabled

April 11th, 2010 § 0

One potential problem that you may come across when putting XHTML code inside your PHP files is that the XML declaration tag may confuse the PHP server.

Short tags

Some PHP servers, including ours, are set up to accept “short tags”, which are shortcut versions of some PHP commands.  For example, on our server, you can either open your PHP script by writing

<?php

Or you can simplify that to

<?

This is a shortcut, “short tag” version of the opening PHP tag that allows lazy developers to type less.

There is another short tag that replaces the normal “echo” command.  For example, a normal echo might look like

<?php echo "arugala"; ?>

And the shortened version of the same command would be

<?= "arugala"; ?>

The problem

A problem arises when we put XHTML code inside a PHP file (a file with the .php extension) because the “xml” tag that we use as the first line of our “bare minimum” XHTML document includes the “<?” in it.

<?xml version="1.0" encoding="utf-8"?>

This confuses the PHP processor, which thinks you intend to use a PHP short tag, which you do not.  You will an error message about a “parse error”.

See this problem in action

The solution

The solution is to encapsulate the “<?” characters inside of a PHP echo statement.  This way you prevent the PHP processor from thinking that those two characters are the start of a PHP opening tag.

<?php echo "<?"; ?>xml version="1.0" encoding="utf-8"?>

See this solution in action

Why you should use PHP short tags

You may be tempted to use PHP short tags.  The conventional wisdom is that it’s a bad idea.  This is because not all servers are set up to support them.

So if you at some point move your code from a server that does support them to a server that doesn’t, your code will cease to work.

This does not fit in with our philosophy of writing code using only those practices that are guaranteed to work with a minimum of fuss.

Class 5 – Document Object Model Cheat Sheet

March 28th, 2010 § 0

Here is an attempt at a cheat sheet for working with the Document Object Model.   This diagram shows the most commonly used objects and their properties and methods.  It is by no means an exhaustive list of every feature of the DOM.

Curated List of Dom Objects

Curated List of Dom Objects

Class 4 – Quiz Results

March 14th, 2010 § 0

sat_results

sun_results

These charts show the breakdown of grades for the quiz.  Here’s a quick chart to convert your scores to percentages:

Percentage Score out of 20
25% 5
30% 6
35% 7
40% 8
45% 9
50% 10
55% 11
60% 12
65% 13
70% 14
75% 15
80% 16
85% 17
90% 18
95% 19
100% 20