[ Silence ]
>> Alright.
This is CS50 the end of week 9.
And this is one of your classmate's home page.
So realize the bar has really been set here.
They have submitted what's perhaps the most annoying song I
too have ever heard, but it is now as usual is linked
on the course's home page.
This is making use of a number of deprecated tags
as the student herself admits.
And it's really was, it seems, a contest between her
and her friends to make the most striking websites possible.
So, this is linked on the home page
for you all to enjoy as well.
But we had some great stuff
in stored today starting with graphs.
So, this is a picture that was actually presented at TED Talk,
one of the famous series of lectures.
It's a little grayed out here, but this fellow
who gave this particular talk essentially screen scraped
like 10,000 Facebook profiles or status updates to see
when people's little heart icons were severing
and people were breaking up on Facebook.
And what he found was that from January through December,
it looks like just after Valentines Day
and over spring break is when most
of your relationships are bound to end this year.
So, keep an eye out of February and March of this year.
It looks like people tend to stay together
around the start of fall semester.
Few of you decided to break up around Christmas time, it seems,
but this is some interesting data nonetheless.
I bring this up one because it's just a little fun to look at,
but also because in the upcoming problems that five
or sorry eight upcoming problems at 8 where we actually play
with some visualizations.
In fact, there's a whole course here
in the Computer Science Department,
Computer Science 171, Visualizations, which is really
about empowering computer scientists
and non-computer scientists alike with tools.
And compelling means of presenting data visually
in a way that the masses can actually understand.
It's not all that helpful to be looking at thousands
of data points generally
in an Excel spreadsheet just adding a bit
of visualization whether it's the familiar bar chart
or something a little more interesting
like the Facebook chart or yet others can really add some pop
to one's presentation but also convey a point.
So this is HarvardEnergy, one of CS50s apps
as I think I've shown before.
And this is entirely we're in on the front end
of a language called JavaScript
which we'll begin to look at today.
And on the back end, it's implemented with PHP and MySQL.
So essentially, once in a while, we synchronize
with the big database Harvard has for all of the buildings
on campus greenhouse gas emissions and the electrical use
and the water use, and so forth, and then we store all
that information in a database, and then we allow people like us
to then search and explore that data visually.
And we do all of these by generating all
of these charts dynamically.
There's none of us sitting there with Microsoft Excel or numbers
of the like and creating GIFs and JPEGs
and then uploading them to the server
and changing this every month.
It's all completely automated.
These web pages written in PHP, query a database,
ask for just a bunch of numbers,
and then output some programming code called JavaScript
that then renders these visuals here.
So for instance, these are the greenhouse gas equivalents
that are omitted by the houses and dorms.
Notice here we have a little toolbar
that you can drag and drop.
And what's neat about this is that all of this is client side.
What you're doing for P Set 7 is pretty much entirely server side
whereby any changes to the user screen,
you're generating server side
and then the browser are showing the results.
Here the servers are not even being contacted.
All the data has been downloaded in advance.
And so when I click and drag on this little knob here,
what's happening is I've written some JavaScript code
that also gets downloaded to the user's browser,
and this JavaScript code is running all the time listening
and waiting for human like me to click and drag
and interact with the web page.
And as soon as it detects such an event, if you recall
that jargon from P Set 0 in our scratch days,
it then responds to that event.
And so the event I just triggered here was click
and drag.
And so what you'll find is
that as your web sites gets more interactive,
and even after the course they get even more dynamic,
you'll find that a lot of programming when it comes
to interacting with users is about this event listening model
where you create a lot of mechanisms in your page
and your application that's just listening for something
to happen and you write functions or methods
as they're sometimes called that who's purpose in life is
to respond to those human interactions.
So, there's actually some neat data in here.
If you jump to something like Mather House, you can dive
in deeper and see more information,
if my internet connection here cooperates.
Come on. Yup.
So what you'll see here is that all
of these charts too were dynamically generated,
and one of my favorites is this one down here.
This is what the author calls a digraph.
It too is implemented in JavaScript.
And not only is it interactive and that you can hover
over these points and immediately see results.
I'm not clicking submit.
I'm not getting a more HTML back from the server.
You can even do neat things and zoom in, for instance, on 2004
and see these same data points rendered all the more up close.
And what's neat is that it's pretty much instantaneous.
And so, a lot of the features you're seeing in Facebook,
in Gmail, and these other web sites rolling out,
are so immediate in terms of the response
because a lot more is being done client side.
And so what we'll do this week is introduce this language
called JavaScript so that you too can begin to implement some
of these increasingly familiar UI mechanisms so not every one
of your web sites has to look, you know, dynamic,
but nonetheless, kind of primitive
like you'll eventually realize
that something like CS50 Finance is.
So, it might all very well be new to you now,
but realize that we're just scratching the surface of some
of the capabilities of today's web, and we're gonna do this
with P Set 8 with something called Google Chart Tool.
So, there's thankful so much free software and free APIs,
application programming interfaces,
out there with which we can then make more interesting
applications by not having to implement everything
from the ground up ourselves.
And so Google, for instance,
provides what they call Image Charts at the top.
These are what [inaudible] would use this for I Saw You Harvard
to generate the male/female statistics that you looked
at for in earlier P Sets.
And then these interactive charts which we'll use
for these P Sets coming up are interactive
and that they're entirely JavaScript, or in a few cases,
Flash-based, but we'll focus on the JavaScript ones,
and you can do very neat things besides the digraphs we saw,
besides the bar charts.
You can even do silly things like-- where's one of these--
piles of money whereby you can generate dynamically bigger
and bigger piles of money relative to the actual numbers
that you provide from your application,
and then there are fun ones as well that are certainly common
on today's web like actually being able to embed maps
of your own local area or something
of interest in your own web page.
This stuff is actually relatively easy
to do these days.
Thanks to these APIs.
So we'll get a taste of that there.
Also, a couple of FAQ.
So one thing that's been a recurring question is something
like this, if I go to let's say go to cloud.cs50.net
until the CS50 P Set 7.
Okay, that doesn't exist.
CS50.net Finance.
So, I'm gonna go to our-- the staff's version of CS50 Finance.
One of the gotchas a lot of you are running into is
that you wanna validate your code using the W3Cs validator.
That's the World Wide Web Consortium.
These are just nice volunteers who essentially over the course
of time, craft today's standards
for various languages among them HTML.
So some of you have been trying to validate you're code
but realized when we say your code-- telephone call.
When you say your code must be valid,
this means not your PHP code per se
but the HTML that it generates.
So if you've found yourself copying
and pasting your raw PHP files code into the W3Cs validator,
that's not what you should actually be doing.
In fact, you're pretty much telling those nice volunteers
all of the good or bad code that you've been writing by doing so.
Rather what you should be doing is visiting your web page
with the browser and then going to say, the--
whichever menu's appropriate, the View Menu or such and going
to View Page Source, and only copying and pasting the output,
because when we talk about the validity of HTML,
we really mean the client side stuff
that hits the actual browser where it's important for it
to be really right so that various browsers all display
it differently.
But there is a gotcha.
So CS50 Finance obviously requires authentication,
and so you can't just paste the URLs of your web pages
into the validator site because obviously, they, like a human,
will be redirected to Login.PHP,
so they can't see all of your HTML.
But realize one of the tools that we recommended
for this problem set is something called Web
Developer Toolbar.
It's a free download for Firefox.
And what it adds to your browser is this little menu here,
things like resize, things
like miscellaneous tools and the like.
And under Tools, you'll see a few options.
One of them is Validate Local HTML.
What's really nice here is that you can log in to CS50 Finance,
visit any of your pages, and then just go to Tools,
Validate Local HTML, and the plug-in will automate the
process of copying and pasting all of your code
into the validator sites.
You don't have to jump through these hoops yourself.
It's a wonderful useful development tool.
And those of you thinking about final projects
and entrepreneurial projects down the road realize
that even simple things
like this are hugely useful these days.
The resize tool here is just a little plug-in
that will immediately resize your browser
to be a specific size.
And this is useful so that if you are one of this people
who has a 30-inch monitor, it's not that great
to design a web site with 30-inch monitor users in mind
because most of people don't have monitors this large,
and so the page, they're gonna have
to scroll horizontally, vertically.
It's gonna be a real mess.
So generally when I develop some web application,
I resize the window to some fixed size like 1024
by 768 pixels across and down and that happens
to still be sort of the lowest common denominator at least
with modern computers.
So thankfully, our screens are getting bigger and bigger.
So realize there are some wonderful useful tools
to take the tedium out of some of these processes.
Alright. So what are the common things
that folks are encountering?
Well, how about messages like this?
So no joke, this happened to me this morning
and there's nothing more infuriating when you don't know
like what you're supposed to do for the day,
when you visit Google Calendar
and you're told Google Calendar is not found.
>> So, this code 404 is something that's not uncommon
on the web either because a page has been deleted
or the user made a mistake.
404 is the arcane number that's been assigned to--
assigned to the concept of
"File Does Not Exist" or "URL is invalid."
In short, whatever URL you try to visit, in this case,
Google Calendar this morning.
Someone accidentally deleted Google Calendar it seems
and the file was not found, index.php or index.html
or whatever language they happen to be using.
Now, this is presumably some other weird
configuration errors.
It's probably no one deleted Google Calendar,
but other popular mistakes that some of you might be seeing
in your own code or others are these.
So, 401 refers to unauthorized.
If you ever visit a page that's supposed
to be password protected in some way
and you've not provided the right username and password,
you often see this arcane code.
403, forbidden.
This usually has to relate to a chmod error on your part.
At least in our context of web development,
you've not chmoded a GIF file or a PNG.
644 or directory 711.
And again, you'll get accustomed
to these arcane numbers overtime, but just refer back
to P Set 7 spec for what command's the right
to fix those.
And 500 is generally pretty bad.
That means there's some non-trivial problem wrong
in the code that drives the page you're trying to visit,
but realized there are dozens of other codes
that relate to status messages.
These are just some of the most popular.
And two more FAQs if I may.
So, you'll see in the spec for the problem set
or rather the distribution code for the problem set
that we make use of things like post or get,
but also we make use of something called session.
So, dollar sign underscore session is another superglobal
in PHP whose purposes in life is really just
to be some storage space for any data you wanna put in there.
You can put any key value pairs.
And in P Set 7, what do we
in the distro [phonetic] code use session for?
>> For the cache ID.
>> The cache ID, yes.
So, once the user logs in, they have a user ID, UID field,
which is just a number.
And so if you look at the logging code that we gave
to you, you'll see that with just one line of code,
we're doing something that looks like this -
dollar sign underscore session "UID" equals 123,
where 123 is actually a variable in the code that happens
to be the current user's user ID.
What's really nice about this session superglobal is
that even though HTTP is what we've called a stateless
protocol whereby you visit a page, little icon spins
around saying downloading page, downloading page,
and then the icon stops because the page has been downloaded,
thereby severing the connection between browser and server,
well, this session superglobal is really neat
because what happens is the next time the user visits a web page,
they are-- their identity is inferred just based
on the web server having seen that user before,
and me the programmer, enhance it, the same superglobal
and the same contents for that particular user.
So even though the protocol is stateless,
I disconnect from the server.
Every time I'm finished look-- downloading a web page,
the session superglobal creates the illusion for me,
the programmer, that I can still store information
for this specific user.
And so even though in my code I'm only ever saying dollar sign
underscore session, I essentially get a unique copy
of this superglobal for every one
of my unique users on the internet.
So, this begs the question,
how in the world does the server handing me the right session
superglobal for a given user?
How does PHP, how does the web server remember
to which user each of these copies
of session actually belongs?
>> Cookies.
>> Yeah. So in fact it is cookies, right?
So, recall our discussion last week of Firesheep,
all these freaking out that people are having over Firesheep
and session hijacking.
When we say session hijacking,
there is the session that's being hijacked
in the context of PHP.
It's called different things in different languages.
But in the context of PHP, this is just the superglobal.
And so, if any of your friends have maliciously logged
in to your Facebook or other account,
what's happening is the web server, Facebook.com,
is presenting to that user the contents of your superglobal.
And so, because your user ID is in there,
because maybe your friend's list and stuff like that is in there,
well that's not necessarily the case, that's how the user,
your friend, is able to see everything
that you are actually seeing.
And so, how is this thing ultimately implemented?
Yes with cookies.
So, when you're requesting a web page
and that cookie is going back and forth across the wire
that we discussed last week that handstamp, so to speak,
that cookie, that big random number is the only thing via
which this abstraction,
this superglobal is actually implemented.
But that's all that it boils down to.
But you'll notice, and this probably will happen to Facebook
in due time, even we,
on the course's home page started doing this literally
after that lecture.
You'll find that everything
about CS50 now runs over SSL-http://.
And we also reconfigured the server to make sure
that anytime we send a session cookie to a user,
a big random number, we will only send
that session cookie if it's over https.
So, if you read in the media that some sites kind of use SSL
but not entirely, generally, they are only kind of using SSL
because they're misconfigured or there's foolishly configured
in such a way that if you manually visit, say,
CS50.net and hit Enter.
Because you're not explicitly saying https,
a foolish server would say, oh,
here's the cookie you'd wanted me to remember.
And in that sense, session can be hijacked 'cause it's not
gonna be encrypted until I get bounced to the https-based URL.
So in short, all of the things you've been reading about
or worrying about on campus are really reduced
to a very simple variable, at least of the web sites written
in PHP called dollar-- dollar sign underscore session.
Lastly, one other trick just to plants the idea in your head,
a lot of you were doing things like this, seek--
dollar sign SQL for SQL which is just a variable name here,
you might do something like this, select star from users,
let's just come up with a quick query.
But suppose you wanna get a specific user,
so you're probably not just getting star from users,
you're getting star from users where user ID equals 123.
But unfortunately, you're not just writing 123 in your code,
the user's ID is of course invariable.
In fact, it's in this variable here.
So, a lot of you are running into the gotcha
where you very reasonably paced that right
into the string thinking alright, well,
this is just a variable, so much like in PHPs--
examples we've seen before, dollar sign underscore session
"UID" will just get turned to 123.
But frankly because of the double quotes
that are inside there, these things here,
because of the square brackets,
PHP just gets confused by this syntax.
So, there are two solutions.
This is not the right way to do it.
You will get some kind of parse error, some kind of read error.
A right way to do this would be to just put
that superglobal variable inside of curly braces
which says here's something special, don't get confused
by the weird syntax inside.
Or you can use
that concatenation operator we saw the other day which allows--
would allow us to do something like equals, quote, dot,
and then you concatenate in this variable like this.
So, all-- both of these latter two examples has the end result
of creating one string that represents the SQL query,
and you avoid this parse error that a lot
of you are running into.
Yes?
[ Inaudible Remark ]
>> It is a designed decision that the authors of PHP made
in that this is ambiguous.
Now that we have double quotes inside of double quotes
and we have square braces here,
they just made the design decision that, um-um,
this could be ambiguous,
we don't want it misinterpret this phrase
and so we will require that PHP programmers use curly braces
to avoid this ambiguity for simpler variables.
If the variable is simply dollar sign X, it is perfectly okay
and arguably much more readable just to say this, that is okay
because there's no weird syntax there, there's no ambiguity,
there's no risk of misinterpretation.
So, it was just a design decision.
And lastly, a reference that can be very helpful.
We point you to this
in the specification quite often throughout the PDF but realize
that PHP.net is one of the reasons that we use PHP
as the language of choice toward the end of the semester
because it's so relatively easy to teach yourself based
on examples and based on documentation.
And frankly, of all the languages I've ever learned
or taught myself,
PHP's documentation is probably the best,
even better than Java's JavaTalk because it's rich
with many more examples.
For instance, if I forget how PHP's date function works,
almost always can you Google it.
You'll find a link leading you to PHP.net and every one
of these pages follows a standard format.
You'll see the name of the function here.
You'll see the version that a PHP that supports this,
which is only relevant if we're gonna be developing a website
on an older server.
This is the prototype for the function.
Even though PHP doesn't require that you specify data types,
the language itself knows that there are different data types.
So, the documentation makes clear what those data types are.
You get a list of all of the parameters
and the format strings and such much
like you would in a man page.
But the most compelling thing,
and the thing I frankly almost always jumped to first,
is that you almost always get one or more examples
where just a real person has written a very common example
with instructions and with comments,
and you can just learn frankly by a lot of examples.
So, don't underestimate the value
of this particular resource.
So, with those building blocks, what can you start to do?
Well, realize the web is getting much more interesting,
and we've introduced this idea of HTML5
which hasn't actually been finalized as a standard,
but the world is really clamoring to implement some new
and fancy features into the HTML language
so that we can move away from using proprietary software
like Adobe Flash, which requires
that the user manually download some additional software
and the like, requires that the program in a different language.
>> And so HTML5, one of its goals is
to make the web even more dynamic and so realize
with this last problems that in this last couple of weeks
where we begin to scratch the surface
of frankly what the web will probably be and remain
for a couple of years.
This is for instance some
of the new capabilities of video in HTML5.
So this is I think the trailer for a movie called Tron
or remake thereof, but what's neat is that built
into the language is this ability--
built into HTML is the ability with code on the client side
to just do things like this, arbitrarily cropped
out some part of it, changed the prospective on the fly
without having to download special software
with which to do all of that.
You can do things like transitions much more easily
which up until now had required plug-ins like Adobe Flash
and I realize much like with PowerPoint,
these things can be very quickly abused.
I'm not sure I would get into the habit
of making my webpage do this all the time [laughter].
It's very easy to annoy users
but you can do really cool things.
This is one-- that-- one-- the TFs just discovered,
it just introduced me to.
This is a chat room implemented entirely with JavaScript.
This is not what you think it is but [laughter].
There is an explanation for this.
It's a little chat room so I'm gonna change my name
to let's say, Sanders.
Oh, here comes the TF
and [laughter] it's a virtual chat room where I can then say,
"Hey, Rose," and we can all meet-- and oh there's Thomas.
"Hello Thomas," and guest 8743.
Now just in my defense, what is this site.
Oh, a lot of you are now in here.
[Laughter] Apparently this is a [inaudible] which is the name
of website which translates to tadpole
but apparently more literally to astral so we're not really all
that [laughter] far away.
But this is all done,
what's cool is this is JavaScript right?
So-- maybe I shouldn't live this up here so long.
[Laughter] That's great, we're talking
to people on the internet.
Alright, this could get bad quickly, so let's close that.
[Laughter].
So frankly, this is really quite cool because up until now,
you would have to write programs like this in languages like Java
or in ActionScript and that's not to say that's a bad thing
but it requires again that the user have special software
namely the Java runtime environment or the flash plug-in
and then you have to actually use multiple languages just
to implement your websites so what's compelling
about HTML5 among other things is the move toward ideally some
more open standards which generally does tend
to be a good thing for the world and certainly for people
who want to program in it.
One-- other one that I thought I'd demo at the TF's request,
this one isn't so misinterpretable.
This is a Macintosh that's falling asleep, here we go.
Give it a moment to wake up.
So I-- we commented to each other
that this is perhaps more impressive to people like us
who know what JavaScript use to not be able to do
but even though the fidelity on the screen here is not
so great, all of this.
This is not a downloadable program.
This is not a flash plug-in.
This is pure JavaScript code that's moving this little fish
around in this 3D environment so this is where we're getting to.
You can really do some neat things.
In fact, one of the CS50 seminars will talk
about web programming.
It will led by Phil, one
of our teaching fellows who's particularly into these kinds
of animations, these kinds of technologies.
In fact, during quiz zero, he called me
over while proctoring quite excitedly because one
of the project still had been working on was this new software
on his own Mac and like many Macs these days,
it has a little eyesight camera built in
and what he did was he wrote code running on his own Mac
that had an image on the screen and as if he moved his body
or face to the left, the image on the screen would then look
at him this way and if he moved over here,
the computer would then look at him this way and this is just
by using this built-in hardware that you know,
statically half of you already have.
So final projects are really a fun chance to put some
of these things to the test.
So it's all about ultimately having the right tools
and so here's one example
of what you can do with the right tools.
So, many of you had a great time battling with hash tables
or tris or the like for problems at six.
This was of course, to implement the dictionary,
and you'll realize-- you'll recall that there's a lot
of low level details there.
There's a lot of chance for error with pointers,
there's a lot of conceptual complexity
at least toward wrapping your mind
around the problem at first.
But realize, once you have multiple tools in your toolkit,
multiple languages, multiple mental models, can you start
to pick from among them and use the right tool for the job.
So case in point, one of the neat things about PHP and a lot
of languages like it is how much you just get
for free out of the box.
There's so many more functions, for better or for worst,
built in to PHP, the mail function, for instances
or this MySQL Functions.
And the upside is that its just much easier
to do some common tasks.
So suppose I want an implement that spell checker in PHP,
not to disappoint after all the hard work you put in.
But if I want an implement to PHP function for load
and it's got to take a variable, namely the path
to the dictionary, its function declaration might look
like this.
It's pretty much like C, except we now have no mention
of data types and we have a dollar sign,
but for the most part, this is the same declaration.
Well, it turns out in PHP,
if I want to implement the load function,
I could do four final dict as word,
hash table word gets true, done.
That is the load function when written in PHP.
So minor white lie, 'cause I've not actually integrated any kind
of error checking.
So just to contextualize this,
I actually need this hash table, right?
So how do I declare a hash table in PHP?
Done. Alright.
So that's my hash table, right?
It's called an array here, but the array function
in PHP returns an array, but what type
of array does it actually return?
In associate of array--
and an associative array is just the formal incarnation
of a hash table, or rather an associative array,
a map between keys and values can be implemented
by what we now know, and have implemented ourselves,
as an underlying hash table using separate chaining
or linear probing or whatever technic you happen to choose,
now, it reduces in higher level languages
to a simple command like this.
As for the check function-- let's see-- the check function,
I think, looked a little something like this,
and I need to return true or false.
So I can just say, if hash table word,
I can then say return true [inaudible] return false.
Done. There's my spell checker, right?
And think about how this is working.
If the load function has indexed into this hash table array
as word-- so word might be apple or banana or peach or pear,
whatever the words were it the dictionary--
each of those fruits is a key, and each of them has a value,
and the value [inaudible] somewhat arbitrarily
but somewhat intelligently chose, was true, because later,
I don't care really where these thing is in the array,
I just want an instant answer saying yes or no, true or false,
this word has been put into this hash table,
into this associative array, so later on, it's suffices to say
if the hash tables value
at the current words location exist is non false,
it must be the case that I put it there, and so,
I get back an answer of true, otherwise,
I return an answer of false.
Now of course, the goal of the hash table, as we discussed it,
was to really whittle things down to constant time,
realistically, you're not gonna get truly constant time.
But what's nice is that now the language,
the runtime environment like PHP, can start to make some
of those hard design decisions for us and save me frankly,
a huge amount of time.
So again, development time, the computer scientist time,
is certainly one of the limited resources that's got to be taken
into account when solving some problem.
But there is a trade off.
I'm gonna go ahead now and run the staff solution,
which is in CS50/pub/solutions /pset6/speller,
and I'll go ahead and run it on, let's say,
one of the larger files, the King James Bible, enter.
So, those are all the words that were misspelled, and it looks
like it took the staff solution .42 seconds
to spell check that file.
So you have among your printouts for Monday this file here,
speller.c, looking through-- sorry, speller.php--
so rather-- no, just speller.
So the name of this file is just speller, and if you read
through this code which I would recommend doing if only
so that you see-- you can learn by example how to write
in PHP code that you've already seen in C, pretty much I sat
down one night and took the C version of the speller,
which was in pset6's distro code, and I just rewrote it line
by line to PHP, and because PHP syntactically is very much
like C, it's almost a line for line translation.
It's a little easier in fact, to do some things,
but then I also sat down to implement the dictionary.
So when dictionary.php, you see more comments,
you essentially see a few subtleties that I have to add
to these functions, but not many more lines of code.
I just added some error checking.
So in short, in these two files, we now have a re-implementation
in PHP of the entirety of problem set 6.
And now, let me go ahead and run this one, speller,
the PHP version on the King James Bible, enter.
So it's not a longer list
of words what's really happening here.
It's actually a slower list of words, alright?
And now, you realize that was actually a little more--
it felt like more than 1.92 seconds,
that's because it takes some time
to actually spit these many characters onto the screen,
to download from the network, show them on a laptop.
But in any case, real time in terms of CPU seconds,
my PHP version took 1.92 seconds, whereas recall,
if I run the staff C base solution, .42 seconds.
>> And this doesn't have to do with load on the cloud,
people using it at this moment.
This just has to do with the language.
So here's one of the tradeoffs.
We've introduced PHP but this is an interpreted language.
We skip the compilation step.
Now that's great because when you're developing project,
you just have to reload your browser,
bam, you see the results.
There's no compiling.
There's no linking.
No assembling.
There's no low-level steps.
You are freer or to just change something, view the results,
change something, view the results.
But the downside of course is that at some point, what you--
you write as PHP code which is not really 0s and 1s.
It's not really English.
It's a programming language.
At some point, that programming code has to be translated
in some form to something a machine,
a CPU actually understands.
And so when you run PHP code, you're actually running it
through something called an interpreter.
So on this Linux system, on my Mac and even
on a Windows computer if you install it,
there is a program called PHP.
In Windows, it'd be called php.exe.
And ironically, it's probably written in C itself.
But its purpose in life is to read PHP-based files,
top to bottom, left to right.
And then essentially figure out what to do at each line based
on the code that it encounters.
But this translation,
this interpretation process simply takes some
additional time.
So there is overhead.
So if you are trying
to implement the fastest spell checker possible,
and by fastest I mean runtime, not developer time, you know,
we made the right decision with C.
If you're actually processing millions of words,
billions of words, if you're implementing Facebook or Google
or really just any real world program even if they're not
as massive as those sites, you do probably do wanna stick
with something like C or C++ or one
of this lower level languages 'cause you can really squeeze
your money's worth and your cycle's worth
out of that hardware.
But if that's less of a concern, if you only have to deal with,
you know, few dozen users per second on the web server,
you can spend these CPU cycles, have slower code but my god,
so many-- so much easier to implement this
and my code is no less correct.
So that is PHP's version of speller.
And notice one trick here, too.
At the very top of this PHP file,
notice I have the special funky sequence of character, sharp,
bang slash user slash bin slash PHP.
This is what's generally known as a shebang or sharp bang.
And this is simply a line that says what program should be used
to interpret this file.
So it turns out there is many different languages you can
write these days, Perl and PHP and Python and Ruby and BASH
and [inaudible] and many, many, many others.
And you can simply tell the computer what should these
various languages interpreters do you want
to use to run this program.
So I have consciously written this program in PHP,
hence the open bracket question mark at the top
and the opposite at the bottom.
But I need to tell the computer what program
to use to run this code.
Or if I did not have that shebang,
I could simply run the PHP program and say,
"Run the program called speller and hit enter."
And much like command line arguments usually work,
that would pass my code in the file called speller into PHP.
But in the context of the web,
we obviously have a web server involved and its purpose
in life is to realize oh,
you're requesting a URL that ends in .php.
I will jump through these hoops for you, invoke the interpreter,
pass your code through it and only spit
out the results to you.
So that's what the web server has been doing for us.
But I realize when it comes time after this class
for your own research or projects or whatnot,
if you ever wanna write a command line program,
you probably not gonna want to reach for C
if really you just wanna get the job done quickly.
You wanna pick a language like PHP or something higher level
that just gives you many more tools for free so that bam,
1 minute later, you know, my PSet
or my research projects, busy work is done.
So, with that said, we now have time
for another interpreted language.
So in the context of a web page, you obviously have tags
and we've seen tags like HTML tag, body tag, head tag,
title tag, div tag and a bunch of others.
But it turns out there is one other that's a little special
called the script tag and that it tells the browser,
"Hey browser, here comes a program, here comes a script."
This is really just an issue of semantics really
but script is essentially a synonym for program.
But a script is usually a program written
in an interpreted language.
And that language here is gonna be JavaScript.
So these days, JavaScript is a language
that browsers understand.
You don't need to download special software,
any modern browser, knows how to read and interpret
and execute a program or a script written
in this language called JavaScript.
Now, JavaScript for some time was generally relegated
to doing really stupid things on the web.
If you think maybe 5 or 6-- 5 or 6 years ago,
the world was plagued by pop-ups and advertisements
that would pop up in Windows, you'd visit some sketchy website
and you can close said sketchy website
because everytime you would, a new page would open.
A new page would open, well, that's thanks
to a programming language that was essentially listening
for the event called Close Page and the moment it heard
that event, what was it clearly doing?
>> Open page.
>> Open page, right.
So this gets very annoying quickly but it all reduces,
frankly to the same building blocks we'll introduce today.
But what's really powerful about JavaScript is not nuisances
like that, but that now you can really interact
with the user on the client side.
So any of these applications we've been using this year,
even the one you might have used earlier on the term,
courses.cs50.net, there is a back end to this website.
There is PHP code, there is a MySQL database,
but anytime you click one of these little plus signs
and instantaneously see that course's description,
you don't have time to make a request to the website,
get back in miniature web page and then show it to you here.
It's instantaneous 'cause we've pre-downloaded all of this data
and we're showing it to you on demand.
And so if you hover over [inaudible] guide scores
and immediately see them, that's simply
because we already have the data.
We just now need to write a program, a script not in PHP
which is way far away now.
It's on the sever in a language called JavaScript that's
listening for these events,
and these events can now trigger responses
like show [inaudible] guide scores or show the like.
And frankly, if you are a fanatic on Facebook
and you see your news feed and all of these new features
where things are changing dynamically and you can click
on icons and little menus pop up, this is all thanks
to a language called JavaScript.
So why don't we go ahead and take our 5-minute break.
>> Alright.
So we are back and we left off with this cliffhanger here.
There is a script tag and this says, "Hey, browser,
here comes a script wherein
in most generally a language called JavaScript.
So what does this language actually do
and what can we actually do with it?"
So I'm gonna go ahead and open up a file called form1.html.
This is among Monday's printouts.
And it looks a little something like this.
There is not much code in here at all.
In fact, even based on our limited experience with HTML,
you can probably figure out what this thing is doing.
It's got a body with a form inside of it
that forms action is dump.php which is just a little quick
and dirty script I wrote to just dump the contents
of what's submitted by this form.
I'm gonna use the GetMethod here.
I've got an e-mail field of typed text, a password field
of typed password, another password field
of typed password, and then a checkbox of sorts.
So this is sort of a prototypical form
on the web that's asking you to interact with it
in a few different ways
and it looks a little something like this.
Let me go into the source, pulls forms1.html.
And I definitely didn't put much time into the aesthetics,
just the functionality.
Now unfortunately, this form is not
that very-- it's not very robust.
I can say, nope, and just type in some random password,
the wrong password again, not even bother checking the form,
click submit, and it does in fact submit.
And notice this is what I happened to type in.
So dump.php, you have a function of--
a function called dump in PSet 7 that just is meant
to facilitate debugging like this.
I'm seeing apparently the contents of what's superglobal.
So get, right?
So if the form is using method equals "get,"
the superglobal that's gonna contain all these key value
pairs is not paused which we consciously use throughout PSet7
so that you wouldn't be passing around financial information
and usernames and passwords.
I'm just using Get Here, so I have just printed
out the contents of $_GET.
How did I do this?
Well, if you've looked at the distribution code,
you'll see that your own dump function just does something
terribly simple like this.
In HTML, there's a pre tag which stands for pre-formatted text
which means even though browsers generally ignore white space,
they only want you to use things like the br tag for line breaks.
Well, if you say P-R-E in a tag, this will now say, inter--
show every little space, every little character literally.
Don't throw anything away.
And there's this other function which is useful
for diagnostic purposes in PHP called print_r, PrintRecursive.
This takes in a variable and if it's got some kind of hierarchy
to it like a hash table would or like a superglobal
like get would, it's gonna show me everything.
And it just shows it in this arbitrary format that's just
very user friendly to read.
So it's a nice trick for debugging just
to see what's going on inside this thing.
Unfortunately, there is no form of validation on this form.
And certainly on websites today, you get yelled at if you try
to register for a site with an invalid username or password,
if you try to log in with the wrong one, if you provide a word
when you're being asked for a number,
if you fail to check a box and sure,
recurring theme on the internet.
Now, you can certainly do server side error checking.
And those of you who've dived into PSet7 know
that you have to do this.
If you ask the user how many shares do you wanna buy
and they type hello.
well you don't wanna buy some indeterminant number
of shares based on that input.
You wanna check, this is obviously not a number.
This is a word.
You need to apologize to the user or you reprimand them
for not providing the right input.
But what's the downside of doing this kind of validation
on the server side in your PHP code perhaps.
[ Inaudible Remark ]
>> It takes longer, right?
Even though the web is pretty quick
on a decent internet connection, you know,
we've seen it take 20 milliseconds to get
from one router to another.
It generally takes less than 1 second, generally less
than 2 seconds for a client to talk to server, you know,
that's still a bit of latency.
>> Latency is delayed, especially perceptible delay
that the user notices.
So, it'd be nice if we realize
that the users typed in something bogus.
Why don't I tell them right away?
Well, HTML and CSS are just about markup and aesthetics.
There's no logical features built into those languages,
but with a real programming language like JavaScript,
can we actually look
at the values the users typed in in the browser.
And without troubling the server, I can immediately check,
wait a minute, those passwords aren't the same.
Wait a minute, that's not a number.
Now, I can't do things like, wait a minute,
that username is already taken 'cause the only way I would know
that answer is asking the server if the username is taken
but for many, many, many types of questions,
can I just answer this by writing code that runs
in the browser and answers these questions for me.
So, my goal here with form1.html was just to demonstrate a form
that does no such validation.
Now, let's start to use this programming language JavaScript
to create a more pleasurable experience
for the user more interactive experience,
whereby you don't have to sit there waiting for the server
to be contacted everytime you have some trivial question.
And so, we now have this here.
This is a form2.html and notice that the bottom
of this file which-- and tell you do have for Monday,
it's pretty much the same thing
but there are couple slight differences.
Notice, I take it upon myself to give this form tag a name
and that's because I wanna be able to refer to it later
in my programming code.
Much like you can give variable's names,
so can you give tags, or more specifically elements
in a web page specific name,
so that you can reference those tags specifically
and not some other form in the page.
And I've also added this.
It's wrapping, so it looks a little ugly here 'cause the
fonts a little big.
But if I just add some temporary white space,
turns out there's another attribute we've not used
yet called onsubmit that frankly does what the name says.
When this form is submitted,
the following code is going to get executed.
So, just like with the style tag,
you can put that language called CSS for font sizes and colors
and aesthetic stuff like that.
With the onsubmit attribute inside of its quotes,
you can actually put programming code,
specifically JavaScript code.
You don't have to write out full functions.
You can just write single statements,
think back the scratch [phonetic].
A single puzzle piece is a statement.
Well, here too can we just put a single statement
in between quotes with the semicolon at the end
and it looks like the function I'm calling here is a function
called validate 'cause I read the manual
and it tells me the onsubmit attribute takes a value
that should be a function
and that function should return true or false.
If it returns true, the form will be submitted as usual.
If it returns false, the form is not gonna be submitted.
This is great 'cause this means now I cannot trouble the server,
I can short circuit a form submission
if the user has done something stupid
like not answer my questions properly.
So, how do I do this?
Well, what is this validate function?
It's not built into JavaScript.
I had to write it myself.
So, let me scroll back up in this file.
It's not terribly long, just a lot of white space,
and here is the very top of the file.
I've got my doc site, my HTML tag, my head tag.
And now notice for the first time, inside of the head
of the web page, I have this script tag.
Now, as an aside, the script tag can go elsewhere in the page.
They're sometimes down sides.
They're putting it elsewhere.
So if you can, it's good to put in the script in the head
but sometimes there's-- problems putting it there.
So, we'll see by example if and when we wanna put it elsewhere.
But the script tag says,
the language I'm gonna use is text/javascript.
This is a thing called a MIME type
which is just a unique string
that some volunteers have decided is the special string
that identifies this language called JavaScript.
If your users happen to be using Internet Explorer or a sort
of specialized browser, you can use other languages,
VBScript for instance in the windows world.
But these days, if you're writing a site that's not meant
to be tied to one browser, it's supposed to be universal,
pretty much the language you've got available
to you is JavaScript.
So, and that's not a bad thing.
It's-- it's quite powerful and rich these days.
Now, this is just a stupid syntactic detail here.
This is one of these things that will take forever to remember,
so I've copied and pasted it almost always.
Slash, slash is a comment.
Slash bang bracket C data bracket.
It's a stupid unique string that just says
to the browser what's following is called character data,
not parsed character data, and this just means
if you see things like open brackets
or ampersands, don't freak out.
They have nothing to do with HTML.
They have to do with math like the less than sign.
The ampersand has to do with the Boolean value
or something like this.
So, this sequence of syntax which you won't see
in every book, this is generally good to do just
so that your code works on all browsers.
This just says to the browser, again, don't get confused
if you see some scary HTML-like syntax,
this is actually programming code.
Now, what is that programming code?
Here's how you implement a function in JavaScript.
It's not, unlike PHP.
JavaScript like PHP is loosely tight.
Even though there is the notion of different data types you,
the programmer, don't-- or have to get into the business
of declaring them specifically.
You can just infer from context.
So, I say function validate open paren,
close paren which means there's no arguments to this function.
And now, these lines are a little long as it is.
I went with the simple but verbose approach
because we can kind of infer from each line
of code what's going on.
So, here's an if condition.
Here's an else if, else if, else if, and then a return.
The syntax realized it's almost like PHP.
It's almost like C. I mean it's deliberate that we've chosen
such similar-- syntactically languages.
So, what am I asking?
If document dot forms dot registration dot email dot value
equals, equals quote unquote.
So, that's pretty verbose.
There are cleaner ways of doing this
but let's reinterpret it literally.
Document is a special global value--
global object as it's called, that you're handed
when you're writing JavaScript code in the confines
of a web page and this gives you access
to all the interesting stuff in the web page namely the forms.
So, document.forms, notice the syntax is pretty much what we
use for structs in C when they're not pointers.
We use the dot notation.
So, document.forms turns out as essentially an object,
so just kind of some structure in memory,
a struct containing all of the forms on the specific page.
Now, how do I get the form I actually care about?
Well, thankfully, I gave it a name.
So, document.forms.registration returns
to me essentially the chunk of memory
that is representing the form that we implemented in HTML.
So, this is what's neat about JavaScript.
Whereas HTML is ultimately about the structure and the aesthetics
of your website, JavaScript now allows you to view your web page
as some in memory data structure like those we played
with with problem set 5 and problem set 6.
So in fact, just to paint this picture here,
let me pull up this snippet of arbitrary HTML.
This is a very simple web page.
It's got the doctype up top, a HTML head title, body tag,
a random link and then an H1 tag.
I just needed something to play with.
But notice that I've deliberately indented things
being nice and pretty printed, but notice too
that this indentation really does imply a structure
to this web page.
HTML, the tag, open bracket HTML seems
to be the most important tag.
Doctype aside, ignore the first line.
HTML seems to be the most important 'cause inside
of that tag is everything else and then inside
of the head tag is something else,
inside of the body tag is something else.
So, we kind of have a structure here whereby the HTML tag
or element is really the root of something.
It seems to have two children, the head child
and the body child and each of those things also has children.
So, it seems to be a data structure much like we looked
at 2 weeks ago, so I can draw this like this.
Alright, you can draw this any number of ways
but I'm gonna come up with an arbitrary thing at the top here.
I'm just gonna say, I need a node of--
there are super root node called the document node.
The very first thing in this page is what's generally called
in industry the root element,
and notice that I have deliberately drawn a head tag
as a child, a body tag as a child.
The head tag meanwhile has a title child
and the title tag kind of does have a child
because there is something inside
of it even though it's not another tag.
So, I'll hang that off of this node
as though it's another child, albeit a textual child,
and then I'll do the same thing for the body tag over here.
And over here with the attributes,
I don't really wanna hang the attribute,
the HREF attribute off vertically 'cause it feels
like that's definitely not a child 'cause it can itself
have children.
So arbitrarily but reasonably,
I'm gonna hang off this node anchor laterally
to the side the HREF attribute.
So in short, I can draw an HTML page as a tree
and this tree is generally known as something called a DOM,
a document object model.
So, what's neat now is that now that we have the ability
to create web pages and structure them with HTML,
you can now start thinking about them really
as from a computer scientist's perspective.
I'm really just building a tree using these tags
but this nesting is implying a hierarchy.
So now that I have a language called JavaScript,
can I actually traverse this tree in memory by going
from root to child to child to child.
So, what we're really seeing here syntactically?
Document.forms.
registration.email is kind of like the process of starting
at the top of this tree and stepping through it, traversing,
trying to get down to the thing I care about.
So, what do I really care about?
The documents forms object, registration object,
its email field,
and specifically the value of that email field.
So, what that's really gonna do for me if we scroll back down.
Here is the very simple input tag that we have here,
and notice it's got a name of email,
and notice it's got a type.
But once the user actually types something
into that field, then it has a value.
So with this JavaScript code up here
in this familiar branching structure,
I'm just asking the question.
If the email's value is blank, yell at the user.
And how do I yell at them?
In JavaScript, there is a built-in, it's slightly annoying
and aesthetically ugly function called alert that takes a string
as its argument and that string is what the user sees
in a little pop-up, and then I return false, why?
Why is validate returning false?
[ Inaudible Remark ]
>> Right. 'Cause they wanna make sure
that the form does not now get submitted.
So, if I return false, that value inside
of the onsubmit handler will return false,
which means the browser will say, oh, the user--
the programmer canceled the submission of this form.
>> But there are some other things the user can do
to be difficult.
If the password one field equals equals quote unquote,
that is if it's blank, I'm gonna yell at the user,
you must provide a password.
If by contrast, password one's value does not equal password
two's value, you must provide the same password twice will
by admonishment.
And then lastly, if it is not, so notice the bang,
if not document.forms.
registration.agreement.checked, I wanna yell at the user that he
or she must agree to our terms and conditions.
So, it turns out that just these form fields, just these elements
in a web page can have a value, a textual value
like the user name or the password.
There are special elements in a web page like a check box
that also have properties but not textual values.
They have Boolean properties like checked.
So, .checked as applied
to agreement is just a Boolean value that tells you,
the programmer, is that check box checked or not.
And so, now you have the ability programmatically
to check these answers without actually looking
in the superglobal called GET or POST.
You can do this all on the client side.
So, the end result is that the user's interaction now looks
like this.
If I go to form2.html, the thing looks the same
but if I am completely difficult and don't type anything in
and click submit, now I get this alert
that says you must provide an email address.
Now, I kind of criticize this thing as ugly because frankly,
every browser makes this window look differently
and this is kind of a stupid way of starting it.
The page at such and such the URL says,
they all look different, so the world tends not
to use the alert function but it is a quick and dirty way
that at least providing feedback,
so we'll start off with that for now.
But we can do a bit better or at least a bit differently.
So notice this too.
Notice I've-- we were in the validate function
in this version of my code as actually taking an argument just
to provide you with this trick as we'll see it moving forward.
So, this takes an argument called F and it looks
like F just represents what?
[ Inaudible Remark ]
>> The form itself.
So, I seem to be calling the validate function not
with an open paren close paren with no arguments.
I seem to be passing in the form itself as an argument.
So, how do you pass a node?
How do you pass a structure in a tree as an argument?
Well, let's look at how my HTML changed.
It's not all that different but notice on the top right,
this time with onsubmit, I'm returning validate of this.
Now, those of you who took AP computer science
or some background course before 50,
you know about Java most likely and you know
about the special keyword "this".
This is a self referential variable that refers
to whatever the thing in context currently is.
So, because I say this inside of double quotes
and those double quotes are inside of these angle brackets
and the tag and question is formed, when I say quote--
when I say this, I mean this form.
So now, I have the ability with JavaScript to also pass
around nodes in my tree, little rectangles like this
as though they really are in memory objects just like we had
in C. If I look at the fourth variant of this,
notice what I can do now.
Let me show you what the HTML actually looks like here
and I'm gonna go to form4.html,
and now notice I cannot even click this button.
So now, I can really be kind of defensive
against the annoying user and now I can require that they type
in let's say a legit email address, type in a password.
I'll use my favorite.
And now notice only when I check this box,
watch what happens at bottom left.
There's the submit button become enabled.
So, you might have seen this on a website but this just boils
down to some simple weak zero Boolean properties,
so let's look at this code in form 4.
Notice now that I have this in my HTML.
I still have the onsubmit handler.
But notice this one.
Again, it's wrapping 'cause my fonts are little large today,
but let's look at this.
If I move some white space in there,
notice that there's another event handler.
Onsubmit obviously does the following
when the form submitted.
Well, for other things, you don't submit a check box,
you submit a form but you do click a check box as you do
to certain other parts of web pages.
So, it turns out that this event handler called onclick also
takes one or more statements separated by semicolon
and this one's purpose is to call a function
when this DOM element, this DOM node is clicked,
so what is toggle?
Toggle is a function I wrote that uses another property
that I read about in the documentation
and it does this, if document.forms.
registration.button.
Wait a minute, what's button?
Well, notice I gave this thing a name.
If I scroll back down, notice this time I gave this input type
which is type equals-- yes, type equals submit.
Notice I gave it a name button 'cause I need to be able
to access this button, this submit button, so I can turn it
on and turn it off, to enable and disable it.
So, here is toggle.
If document.forms.
registration.button.disabled is true,
so here's yet another property.
So, this is what's really neat.
Even though we've just been writing HTML for structural
and aesthetic reasons,
all of these tags we write do get interpreted by the browser
and everytime the browser encounters a new tag,
it essentially calls the equivalent of malloc [phonetic],
malloc-ing enough memory for that node that then represents
that tag inside of RAM and it associates with some
of those node certain properties based on their type,
this one being a submit button,
and so that submit button has a special property
called disabled.
And if that is true,
then obviously the button is disabled.
You cannot click it.
So, what I'm doing here is if the button is disabled,
make that not so, like make that false.
Else, if it is not disabled, make that true to disable it.
So, it toggles the states of this variable
by using just another event handler
and my validate function is identical.
Now, how did I actually do this down here?
It's worth noting this 'cause this is kind of a stupid reality
of modern web programming.
Input disabled equals disabled.
So, this is the paradigm you actually see.
Back in the day with HTML 1 and 2 and earlier versions,
you could have attributes in a tag
that did not have an equal sign or quotes.
This is largely frowned upon these days.
So, the world realized, wow, we still wanna have the ability
to disable an element but we need some value.
Now, a reasonable person might have said something like true
or one or something but they decided let's not come up with
yet another value, let's just say value equals itself.
And so you'll see this throughout the literature,
but that just means by default, this button this disabled.
Notice if I get rid of that and then re-save this page
and reload the browser, notice that this page is no longer--
is it saving properly?
Oops. My-- oh, I think I'm-- oh, I'm changing the wrong version.
So, if I were actually visiting the right version of this file
with this particular browser,
you'll see that the submit button is actually working.
But, you know what, I can cheat and save myself here
for some definition of save.
I'm gonna go to inspect elements.
Notice this is our friend Firebug, and what's really nice
if you like to geek out with this stuff,
notice I will just manually go in here.
Come on, change that, there we go.
So, this actually illustrates the point.
So, let's assume that was deliberate, that mistake I made.
So, this actually illustrates the point which is
that you might be really excited that, wow, I don't have
to write all this damn PHP code
which have been confusing me the past couple of days.
I can just start embedding this on the client side
and the upside too is that the user gets a better,
faster experience.
But unfortunately, if the--
the user has a modicum of technical savvy
or has free software installed,
any of these client side defenses can be
completely circumvented.
Clearly that I just disable the disabling of the button just
by tweaking the code, you will know already from P set 7,
you can pretend to be a browser and request things
like Yahoo's web page but doing it from a PHP context.
So you have to realize that with form validation
or any client side code, you cannot trust
that the user will execute that code as you wrote it.
You have to assume that they're still gonna try
to insert bad stuff into your website and so still these--
this server side protections that we've been preaching
for problem set 7 remain a necessity.
So unfortunately, you have to do both.
The upside of one is better user inter--
a better use your experience.
The upside of the other is that your website remains safer.
So, let's take a look at now one other capability of JavaScript.
So, back in just a few years ago, frankly,
JavaScript was a pretty annoying language.
It created all these pop-ups in the world.
It would have these ugly alert messages on the website.
But now that you can really program against the DOM
of a web page and do increasingly powerful things,
you can create much better user interfaces.
For instance, the one I always turn to only because it was one
of the first sites to do this, the fact that you can click
and drag on Google Maps was really groundbreaking a few
years ago when everyone else like MapQuest
and Yahoo was the old 1990 style of click the up arrow
and then we'll get you a new tile.
Click the left arrow, then we'll show you over here.
I mean, up until a few months ago,
that's what Harvard's map looked like too
but they too have transitioned
to what's called an Ajax approach.
And if you do this fast enough, if I click and drag,
first let me zoom in, if I click--
well now, I've got really no interesting earth
in this part of the world.
[Laughter] So, if I click and drag really fast,
you might be able to see what's happening at the top left.
Briefly, there are little gray squares and that's
because those tiles,
those images haven't been downloaded yet.
So, it's really going on beneath the--
underneath the hood here with Google Maps.
If I pull up Firebug and go to the net tab,
notice everytime I click,
look at how many requests were just induced?
Now, a normal user doesn't throw the map as I just did
because my little clicking and dragging just induced 36 more--
36 more HTTP requests.
And if I zoom in on each of those, each of those happens
to be a tile, a part of the map.
So, Google is using JavaScript to programmatically listen
for user clicking, user dragging, user letting go.
>> And the moment that happens,
they quickly contact the server using HTTP.
Turns out with JavaScript just like PHP,
you can make HTTP request.
A response comes back, an image comes back and voila,
that image then gets inserted into the web page.
So, how can we begin to do things like this?
Well, let's take a look.
I'm gonna go to let's say ajax1.html
and I'm gonna pull this file up in my browser as well.
And notice this, it's a pretty simple website,
it's sort of a very primitive version of CS50 finance.
But, notice, I have a text field here
for symbol and then get quote.
And if I go ahead and type in something like GOOG
for google, click get quote.
Alright, interesting.
It appears that at this moment in time,
according to Yahoo Finance,
Google's stock is worth 617 dollars and .0415 cents.
So let me go ahead and see how we did this.
Well, first, let's look at the HTML down here.
It's actually a pretty simple web page, right?
This did not take much effort to write.
I've got a body, a form, interesting, an onsubmit handler
and then also return false.
So, it seems that I'm now using the idea of a form
to have a purely client side experience.
The whole page is not going to reload, and this too is one
of the themes these days with web programming.
You might very well still be clicking buttons
and check boxes all the time on websites
but it's increasingly rare that the whole page reloads
and instead, you get like a little progress bar
or spinning icon and then bam, more content appears.
Facebook, again, case in point.
If you scroll the bottom of your news feed, there is usually
like an older posts link.
If you click that, it doesn't reload the whole page,
it instead just changes I think to some kind of progress bar
and than bam, a second or two later, more posts.
It's using JavaScript, listening for your mouse click.
When it hears it, requesting more data from the server
by HTTP, gets back more HTML and it just adds it
into the existing DOM into the existing tree structure.
So how is this happening here?
Well, notice, I've got an input element.
This time, I gave it an ID so you can use name and ID
for partly similar purposes but ideas a bit better
because it means it has to be unique.
So if you know you specifically want that element in a web page
to be accessed with JavaScript if you have given an ID, now,
you can insure that when you get that element, you're getting
that one and only that one, and then I just happen
to submit by-- that looks like this.
So the magic must derive from this ID on my input.
So let me scroll up here.
So there is a bunch of code here, but fortunately, libraries
and APIs have made this kind of programing easier.
but I'm doing it old school,
sort of did the low level way just
so we can see what's really going on.
Here is my head tag, and here is a script tag therein,
and notice that I'm declaring what appears
to be a global variable, global in the sense that it's not
at the top of my file, but it is at the top
of my JavaScript code.
It's at the top of my script tag, so in that sense,
this is a global variable, XHR, and I'm initializing to null
so that it just has some known value, XHR is deliberate
because it turns out modern browsers support a special
feature in JavaScript called the XMLHttpRequest object,
kind of convoluted name, but this is a special object,
a special feature of JavaScript that allows you
to make http requests, get back the response, and then show them
to the user or embed them in the web page.
So the magic is ultimately gonna derive from this feature
of recent year's browsers.
So here is my quote function.
It's a little-- got a little bit of new syntax here.
The function called quote first does the following.
So this is a feature of JavaScript, PHP supports this
as well, as does java and C++ and other languages.
There is this notion in some languages of exceptions.
And actually, let's see, did that have it-- yeah.
So we haven't really seen this yet.
So in JavaScript, there's this notion of an exception,
and exception is a way for function
to say something bad happened
without returning some arbitrary value.
A lot of C functions return zero if there is a--
return negative one if there is problem,
or they return some special value if there is a problem,
PHP meanwhile, tends to return false if there is a problem.
This is problematic, because suppose you're writing a
function in C and you wanna able to return a number,
well unfortunately, if something goes wrong,
you can't return a number because maybe
that is just the actual answer you're expecting.
If the function in C you're writing is suppose
to add two numbers together, well, what if the answer
of adding two plus negative three is negative one,
does that mean an error happened,
or does that mean the math was correct?
So in short, with C and languages like it,
the way that we implement error handling is pretty hackish,
right?
We return some special value and we have to check
for that with a condition.
Now, in languages like JavaScript, you have kind
of this back channel for signaling errors,
and it's called exception handling.
And with this model, what you do is you call a function as usual.
In this case, I'm writing a line of code like this,
XHR gives me a new XMLHttpRequest object.
This is new syntax for many of you.
But for now, just take for granted--
take it for granted that this is what you have to type
to get a new object called XMLHttpRequest.
But notice, I'm only trying to execute this line of code.
So what's happening here is if something goes wrong,
like there is no internet connection
or the browser is too old to understand this,
what's gonna happen is this line of code is going
to throw an exemption, which is like a special variable,
special object that represents an error,
and someone playfully decided the corresponding syntax would
be catch.
And so, you write code that catches that error to detect
that something bad has happened.
Now, you won't need to write this much code yourself.
In fact, for the AJAX part of any code you write,
odds are you can abstract these details away
with a library, as you will.
See but for now, just realize this is what this is all about.
Now unfortunately, this is a stupid reality.
So as is often the case in the web world, different companies
like to do things different ways, and this line
of code will fail on older internet explorer browsers
because Microsoft decided
that the syntax would be this instead.
So the only reason I have to do this particular try and catch,
the only reason, lots of websites have
to do this these days is again,
because companies don't play nicely on the playground
when it comes to coming up with the standards.
So we're stuck with writing more lines of code than is ideal.
But the point for now is if at this point in the story
that variable is still null,
it must be you're browsing my website would like netscape1.0
and it just doesn't work, so I'm gonna catch that, yell at you,
and just return immediately.
But that generally does not happen these days.
So notice what I do.
It's not much line-- not much code at all.
I declare a variable, so in JavaScript,
there is a special keyword called var,
that says give me a variable.
It's not a data type.
You just say var x, var y, var url.
And now, notice in JavaScript, I assign a valuable--
a value just with the equal sign as usual, "equals",
what's going on in here?
Well notice, I'm creating a string that starts with
"one.php?symbol=something".
So this is my way of constructing a url,
and then appending to it, some parameters.
This is what's also nice about get.
You can construct get request on the fly in code
because you just have to create a url,
and a url is just a string.
So what am I doing?
I'm creating url that starts with "1.php?--
which says, here comes the parameters-- symbol=", and now,
this is a minor nuisance in JavaScript,
the concatenation operator is plus, whereas in php, it's dot.
Different philosophies, does the same thing.
So this is gonna concatenate onto the end
of this string, what document?
dot get element by ID "symbols value".
Now again, new function, but it really does what it says.
And this is one of the nice things too about JavaScript.
Most functions are just names very aptly,
get element by ID returns to you the objects in memory
that represents the symbols input field and dot value
like before, just gets me its specific value.
So in the end, if I typed in goog,
what does this actually do?
This creates a variable forming, called url, and it stores
in that this "string" here that is essentially the end
of the result of this line of code.
So now, if I haven't specified http:// and then cloud.cs50.net,
that's gonna be assumed, because just like in web pages,
you don't have to put urls
in your image tags and in your CSS tags.
You can just say a relative url, so this really is going to me
in something like in implied cloud.CS50.net/something.
So I don't need all of that mess at the beginning.
It's gonna inferred.
So what actually happens then?
Well, notice with this, three lines of code,
I got to do something really powerful.
1st, I'd say XHR on ready state change, robust but clear--
what will be clear, equals handler, come back to that
in a moment, XHR.open, what method do I wanna use?
Gets, unfortunately, in this case, it's capitalized,
but it's the same thing.
What url do I wanna get?
And then true is a good thing to put here,
it means a synchronous.
AJAX means Asynchronous JavaScript and XML.
This just means don't put
up a stupid progress bar, something like that.
Just go get it and was turn the value as soon as you're ready.
It's a nonblocking call in computer science speak,
and then lastly, send.
Now, it doesn't matter so much the specifics for now,
what's the high level take away.
Those four lines of code together create a url,
then create a connection to the web server, cloud.cs50.net,
and then send those parameters.
That's it.
So it makes an http request.
We did the same thing in PHP code.
If you look through helpers.php,
we use a file called file_get_content.
This function in PHP does exactly what we described here
in JavaScript code, and it does it a little more cleanly.
But the magic now is this.
Notice that I'm saying XHR.onreadystaychange=handler.
What's need about JavaScript-- and you can actually do this
in C even though we never exercise this power,
you can do this in PHP too--
you can pass functions around as though they are variables,
as though they are pointers.
So you can actually pass a function to another function
as an argument, or you can assign
to a variable the name of a function.
>> So it turns out that handler here is the name of a function
that I happen to write down--
and we'll see what it does in a moment--
and as these long words kind of suggests, when the states
of this special object, HXHR, changes, call this function.
So in other words, here is magic of AJAX.
You make a request and you tell the browser
which of your functions to call when the answer comes back
from the server, whether that's 20 milliseconds later
or two seconds later or even half a minute later,
that functions gonna get called,
and it's gonna be passed what the browser gave it.
Well, what does this function do?
Well, I've read in the manual
that if the variable called ready state=four--
it's just arbitrary, but I copied-paste it--
and if the status from the web server is 200--
we've seen earlier today some bad statuses,
401, 404, 403, 500.
200, we never see, 'cause it's good.
Anytime you request a page on the web that comes back,
a secret number, namely 200, comes back.
So now, I'm gonna do this, alert of xhr.response text.
So a lot of words that just came out of my mouth,
but they take away is that this function handler got called,
and it alerted the user by passing in this value.
So what's actually inside of this text here,
8xhr.response text, is whatever the web page actually spit out.
So what did it spit out?
Well, let's mimic this request ourselves.
I said that it's gonna ask for "one.php?=goog".
Well, just do that ourselves, I saw a "one"
in here a moment ago, "one.php".
Doesn't seem to do anything.
But if I'd add this myself up top, ?symbol=goog
and then hit enter, it looks like this PHP script I wrote,
its purpose in life is just to contact yahoo, get a number,
and then spit it out to the screen.
So that's where that's coming from.
Unfortunately, just using alert's not all that sexy.
But if we look at the second version,
we can do something a little more familiar
with the place holder.
Notice that I can instead embed a response right
into a web page, slightly more sophisticated.
Notice that I can do something like this
and get back multiple pieces of information
with a sexy little progress bar.
Alright, there it is.
It acts-- the server is actually not slow,
if you look at what's going on there, just a--
turns out, if you go call-- where is it, "2"--
turns out if you call sleep five,
it will sleep for five seconds.
So, that's a useful simulation.
But let's see where else we can go with this.
Let me got to AJAX four, type in goog, get quote.
Alright, that was actually underwhelming
since that's a step backwards, but I'll skip that part here
and type in goog here and get quote,
so what's actually working here, well frankly,
I think the sexiest was number three.
So let's just look at this one.
So get quote induced this really fancy progress part
that I made, or downloaded.
So let's see how this thing works.
So in AJAX three, we have the following html.
Html is almost the same-- but notice what I've done,
and realize there is many ways I've could have done this.
I've got a form, I've got an [inaudible] handler,
and a function call returning falls.
So the form it self does not get submitted,
my JavaScript kicks in, I've got an input field for symbol,
and then notice this, I've got a div who's ID is progress,
then I'm using a CSS trick,
turns out there is a CSS property called Display,
and if you set it equal to a value of none,
it literally does not display that node.
So you know what that node actually is,
it's this [inaudible] here, pleasewait.shift.
So even though it looks like animation, this is just sort
of a 1990 style animated shift
that just always looks like this.
So what my code must be doing is that symbol--
that progress bar is always there,
but by default, it's hidden.
So what I'm really doing is this,
inside of my JavaScript code here for version three,
I create the url as before, but then notice this trick.
I get the element by ID of progress,
I get it style property, which relates to CSS, specifically,
its display property, and I change it to "block",
which is ironically, the opposite of none.
And then in my handler function, which recall is what gets called
when this response comes back, I say document, I get element
by ID progress, that style that's display equals none.
So again, using this very simple primitive
of manipulating the dom a little something that looks like this,
I can now control the entirety of the web page.
And even though this was a lot, pretty soon and pretty fast
for all of us, these are pretty much all of the fundamentals
with which you're most favorite websites these days are
implemented, including Facebook.
So anytime you see Facebook's on progress bar, realize,
that is an XmlHttprequest object.
We'll see you on Monday.