fliesen ideen eingang
>> [music playing] >> david malan: this is cs50. this is the start of week nine. and this is what would havebeen mr. boole's 200th birthday. so this is the fellowsto whom we've alluded quite some times about usingboolean variables true and false, 1 and 0 and such. and this was google'stribute to him today. he would have turned 200.
so if you'd like tojoin us for cs50 lunch, take a look at the linkon the course's website. and such faces and friends asthese await you here in cambridge. faces like these await you in new haven. and, in fact, ken innew haven kindly made what's called an animated gif of elihere at a recent lunch-- a gif is yet another graphical file format,with which you're familiar-- that looks a little something like this. so just a sequence of-- ok.
no one here in cambridge is laughing. but in new haven, thisis really funny, right? all right. >> so do join us there. here at harvard,specifically, this wednesday, if you're a sophomore or freshman even--or even junior-- thinking of making a switch into computerscience, know that there'll be a cs advising fair thiswednesday, shortly after class at 4:00 pm in the computerscience building maxwell dworkin.
we'll put this on the course'swebsite by tomorrow, as well. donuts, i'm told, will be served. >> all right. so funny story-- i was pokingaround on the internet, and i found some old archivesof my former website. and it turns out-- around thistime, it seems very timely since i gather that the uc electionsare about to gear up again. so i ran for uc, lost miserably. and maybe this was in part why.
so this was my website at the time. for some reason, i thought it wasa good idea, before telling people what my platform was and why theyshould vote for me, that they have to click to enter to find out thatinformation, which in retrospect is kind of creepy. i don't really know what that was. >> but it certainly didn'thelp my campaign. i also found that by senioryear-- i had this muppet calendar. muppets were kind of in vogue back then.
or maybe they weren't. i had a muppet calendar back then. and i thought it'd be cool to namemy computer on harvard's network frogman.student.harvard.edu. at the time, we all had uniquelyidentifiable host names. and you could choose some vanityname instead of your own name. and i went with frogman for some reason. >> and then i started-- i spent a lotof time clicking through these links this morning.
and this was my about page,which now kind of seems adorable. but it also testifies to justhow far technology has come. i mean, back in the day,a 486 was something. these days, it's super, super,super slow and well less than you might have in yourown pockets these days. there's more on there thatwas even more embarrassing. so i'll leave it at that. but that was my firstforay into web-- oh, no. that wasn't.
my first real foray into web programmingwas this site, which i just forgot. at some point, i learned how tomake repetitive background images. and so i found this tiling effective,like hockey player, football, and golf ball, or whatever that isfor the frosh ims website. and this was actually, genuinely thefirst web-based project i took on-- i think maybe sophomoreyear, junior year-- after taking cs50 and cs51, oneof the common follow-on classes. i noticed in lookingthrough the archives that one of my successors andfriends, lee, kind of changed
the copyright to himself. but this was indeed something thati should own the embarrassment to. but at the time, thiswas the first website, as i said a few weeks ago,by which freshman could register for intramural sports here. and so it turns outthat background images like that are not such a good idea. but the web was new, andwe were all experimenting. and this is what iapparently did at the time.
so without further ado, we switchgears today to give you, really, the final piece that you might findespecially useful for final projects but also that will start tomake the whole world wide web feel a little bit more understandable. indeed, we're going to introduceone more programming language called javascript that's similarand different in different ways from languages we've looked at thus far. >> so c, recall, is this compiled language. you've got to run it through a compiler.
you get source code to objectcode, or zeroes and ones. and those are zeroes and ones thatyour cpu, central processing unit, actually understand. php, by contrast, isn'ta compiled language. it's a what? it's an interpreted language. so there's some programcalled an interpreter that has to read it-- top tobottom, left to right-- and figure out what all ofyour syntax does and means,
whether it's a loop or a conditionor any other number of programming constructs. so that's an interpreted language. >> then we introduced html. and html's not even aprogramming language. we'd call it what? a markup language, which is justa sort of fancy way of saying it doesn't have programming constructs likewe saw even back in the day of scratch. there are no loops.
there are no conditions. it really is a languageabout marking up your data and formatting it orstructuring it in some way. >> css, meanwhile, similarlynot a programming language. it's even more aesthetically oriented. and it allows you to sort of fine-tunethings like font size and colors and placement and all of that. then we had >> sql.
so sql is indeed a programminglanguage in some sense, albeit tailoredspecifically to databases. but even though we only introduce you toselect and insert and delete and update and a couple of others,turns out you can actually write functions orprocedures, as they're called, in sql that look and actquite like php and c functions. so know that those exist. but we don't even bother with themas we just scratch the surface here. and then javascript, the last ofour languages formally introduced.
so javascript, too, isan interpreted language. and those familiar, doyou want to distinguish it with some characteristicfrom both c and php? what makes it different? >> audience: it's not compiled. >> david malan: say again? >> david malan: it's not compiled. so it, too, is interpreted. so it's not compiled.
but that makes it a little like php. but it's still different fromphp in some striking way, at least in the way we'll use it. yeah? >> audience: it runs client-side. >> david malan: it runsclient-side, usually. that's indeed the distinguishingcharacteristic for us right now. c was server-side in the sensethat we did everything in cs50 ide. php thus far has beenserver-side insofar
as it, too, gets interpreted--not compiled, but interpreted-- inside cs50 ide, which of course isjust a server or servers in the cloud. >> but javascript, eventhough you you're going to start writing it for, say, pseteight and maybe final projects-- you're going to right it incs50 ide and save it in files within cs50 ide, cs50 ideand, in turn, the cloud servers on which it's hosted, are not goingto interpret or execute your code. rather, it's going to be sent inunaltered form down to the browser. and it's then going to be ieor chrome or firefox or safari
or whatever that actually interpretsit, top to bottom, left to right. so the key distinguishingcharacteristic for today is that javascript is client-sideand php, for instance, has been server-side. now, this has interesting implicationsfor, like, intellectual property and who can actually see your code. and indeed, you can goon the web and see most any code that someone haswritten in javascript. sometimes it's readable,sometimes it's obfuscated.
but more on that in due time. >> so javascript, nicely enough, issuper similar, syntactically, to c. and much like php,there's no main function. if you want to start writingjavascript code, as you'll see today, you just start writing it. but it is, you'll see, particularlyuseful in the context of web browsers. however, my littledisclaimer-- usually earlier-- was to say that you can increasinglytoday use javascript server-side using a fancy framework called node.jsthat some of cs50's own applications
are written in. check 50 actually uses node.js. but we're going to focus onjavascript client-side here on out. >> so here is a set of conditions in php. sorry, in-- actually, thatstatement, too is correct. here is also a set ofconditions in javascript. syntactically, it isidentical to c and to php. mr. boole's expressions are,similarly, syntactically identical to both c and php.
we also have switches injavascript that look identical. we have for loops that arestructured identically, while loops, do while loops. >> this one's a little different. php had the for each constructthat you might be using or will use in pset seven, perhaps. javascript has this special version offor where you literally say something like for variable key in object, whichis a very succinct way of saying, if i've got an object-- and we'lltalk about these again in a moment--
and i want to iterate over allof the key value pairs inside, i don't have to figure out how tonumerically index them with zero, one, two, three. >> i can literally say this. and on each iteration, javascriptfor me will update the variable key to be the first key, then the next key,then the next key, then the next key, and so forth. and i can get at its value by treatingan object in javascript, as we'll see, as though it's anassociative array in php.
indeed, if you finally wrapped yourmind around what an associative array is in php, you can think of it for now asidentical to an object in javascript. but that's a bit ofan oversimplification. >> arrays look, nicely enough, identicalto php except for one character. there's one thing missing herethat we did see last week with php. what's omitted? no dollar sign. so we're back to amore normal world where variables don't have dollar signs.
but you do prefix themwith var, typically. and var means variable. and much like php is looselytyped-- whereby there are types, there are numbers and stringsand floats and so forth-- javascript similarly has types. but it's loosely typed in that we theprogrammers don't have to specify them. we just have to be awarethat different types exist. >> variables, meanwhile-- here's howwe might declare "hello, world" as a string.
notice it's identical tophp but no dollar sign. and this is something we'llstart seeing more today, whereby you have an objectwith keys and values. and if you want to tryto infer from last week-- the syntax is a little different. but a little sanity check-- how manykeys does this object seem to have? so i see four. i see two. >> so it's actually two.
so this is a collectionof two key-value pairs. the key is symbol whose value is fb. the key is price whose value is 101.53. so those are two key-value pairs. and remember, php-- and this is againjust sort of syntactic difference. it's not all thatintellectually interesting. php might have written this samething as follows-- quote, equals. and i change these to square brackets. and then i change this toa quoted word, "price."
and then i don't use a colon. what did i use last week? yeah, the equal signarrow funky notation. >> and then i did the same thing here. same thing here. and that's all. so it's fine if this hasn'treally sunk in to memory just yet because it's reallyintellectually uninteresting. it's just syntactic differences.
but the ideas are exactly the same. inside of this variablequote in javascript is a collection of key-value pairs,one of which is symbol, one of which is price. and i can get at those valueswith the following syntax. just like in php, i coulddo something like-- let me make this box a little bigger. just like in php, i couldmake this-- oh, dammit. come on.
>> just like in php-- ok, we'lljust use the presenter notes. just like in php, i cando $quote$quote["symbol"], and this will get methe value of "symbol." in javascript, it's going to beidentical, whereby i can just do this. the only thing that'smissing is the dollar sign. >> so nicely enough, then, there'snot all that much new syntax. so what today we focus on, really, issome of the ideas and the applications. and the first suchapplication that you might have seen if you dived into psetseven already is this syntax.
so in pset seven, if you'veseen or not seen it yet, know that there's a file that we giveyou called config.json-- javascript object notation. why? we wanted to be able to provide you witha template with some key-value pairs. we wanted to be able to give you a listof the host, the name of the server. we wanted to give you aplaceholder for your username and a placeholder for your password. if you're not seeingthis yet, not to worry.
more on this in pset seven[? spec. ?] and then, obviously, we want youto fill in the to-dos because when you log intocs50 ide, each of you have your own username and password. >> so we could've used a half a dozenor more different file formats. we could have used a .txt file. we could used a csv file. we could've used anini file, an xml file, a whole bunch more acronyms thatyou might not have ever heard.
it's kind of arbitraryat the end of the day. but super popular these days is a textformat called json-- javascript object notation-- that looks like this. it's a little cryptic,but notice the patterns. you start with an open curlybrace, and you end with the same. inside of that is something. it's a key-value pair. so this is an object that i'mlooking at on the screen here that has one key, which has one value.
and just inferring based on theprevious pattern, what's the key here? database, the thing tothe left of the colon. >> now, the value happens to bea multiple lines this time. but the value starts with a curlybrace and ends with a curly brace. so what would you propose is thetype of the value of database? a dictionary or, just moresuccinctly, an object. right? this is kind of a data structure thatcan use other structures within itself. so if this whole thing we'recalling an object-- and an object
is just a bunch of key-value pairs-- thevalue of database itself is an object. the value of database has a whole bunchof key value pairs, the first of which is host, then name, thenusername, then password, each of whose values, meanwhile, it'sjust a boring string in double quotes. >> so even if that's notsuper clear just yet, know that this is just astandard, fairly boring way of storing data in a standard format. but the common mistakes youmight make, even in pset seven, are little stupid things, like if youaccidentally omit the comma there.
that's going to result in the filenot necessarily being readable. if you accidentally omit things like thequotes, it's not going to be readable. so it's a pretty nitpicky file format,but it's one that's super common. and we happen to use it, even thoughyou don't use any javascript otherwise, in pset seven. so remember this picture. we talked about, in html, thatthe code might look like this. this is the hypertext markup language[inaudible] for just "hello, world." but then we proposed awhile back that if it helps,
you might want to start thinkingabout this already as a tree. in fact, the indentation that weuse just for readability's sake or for style's sake onthe left can kind of be translated into this tree, where youhave some special root node that we'll generically called document, below whichis the root html element or tag, html, which then has twochildren, head and body. >> and then in turn, head has a title. and title has a text value. and body similarly has a text value.
so if you're comfortable sayingthat yes, you could take this html and draw a picture likethis, the right-hand side is a nice mental model because nowthat we have javascript, a programming language that browsers canexecute and interpret for you, it turns out that whatwe're about to do in code is start to manipulate thistree structure in memory. we don't have to buildthe tree in memory. we don't have to do sort ofpset-five-style data structure complexity.
the browser, nicely enough, uponinterpreting html top to bottom, left or right, is literally going tohand us the equivalent of a pointer to that entire tree for free. it does all of the hard work. that's what mozilla and appleand others have done for us. >> and with javascript are we going tobe able to control and change and do interesting things tothat tree, otherwise known as a dom or document object model. what kinds of things?
well, it turns out thatin javascript, there's this laundry list ofevents that can take place. and we haven't really used thatword since week zero and pset zero when we talked about scratch. most of you probably didn't usean event in your scratch project. but you might recallthe simple marco polo example, where we had twosprites, one of whom said, marco. the other of whom then, upon listeningand hearing that event, said, polo. if not, feel free tolook back that far back.
>> but this is just tosay, and you can kind of infer from the names of thesethings, javascript, it turns out, is going to give us a way to listenfor mouse going down or mouse going up or key going down or keygoing up or onsubmit onselect or onresizing something. in other words, any physical actionthat a human can take with a browser that you do every day, you can writecode for that listens for those events and then does something appropriate. >> for instance, if you use google maps,what happens if you click and move
the mouse, typically? if you click and drag? exactly. the map starts to move. so you can sort of see what'sover here, what's over there. and how does google implement that? well, presumably, they'reusing a couple of these event listeners, one thatsays, listen for on mouse down-- so when the user physicallypushes his trackpad or his or her mouse
down. and then we're looking forsomething like movement or some other event thatallows us to capture drag. and in fact, drag is similarly in thisdot dot dot list of possible options. >> so this is going to be a powerfulway to start responding to the user even before he or she actually clickssomething explicit like submit. but we're going to introducea couple topics to get there. but first, let's transitionto some actual code. so i'm going to goahead and open up dom-0,
which is a very simple examplehere that if i zoom in simply has this input here for me. and i'm going to go ahead and type in"david" for my name and click submit. >> and then, albeit sort of cheaply, ihave this prompt that pops up that says, "hello, david!" so this is kind oflike our "hello, world" that we did awhile back in c andeven in php because i've dynamically outputted my name. i can do someone else's name here.
i could simply change this to,like, hannah, click submit. and indeed, the little pop-up changes. >> now, pop-ups are one of themost abused features of the web. and in fact, back inthe day pop-up blockers came into vogue because youwould go to some website-- perhaps a questionable place--that would then suddenly start peppering your screenwith a whole bunch of pop-ups. and so this ability to pop upwindows in front of the user has not been particularlywell-received by humanity.
so that's why you seethis prevent thing, which just makes this whole thing ugly. so we're going to need abetter way to prompt the user. but for now, that seems to work. so just intuitively, whatseems to be happening here? i go ahead and click submit, andthen something's happening, clearly. but what's not happening that did happenlast week any time i clicked submit? what didn't happen on the screen? sorry?
reload. the url didn't change at all. i said this was dom-0,and i'm still at dom-0. normally, we'd get changed to some otherurl, like register.php or the like. >> but even when i dismissthis thing by clicking ok, notice that the urlstays completely put. and, in fact, if i'm a littleskeptical, let me open up chrome. let me open up the network tab. and notice it's blank at the moment.
let me go ahead and resubmit maria. there's no network traffic whatsoever. so there's no http. >> so indeed, if i look at the source codefor this-- let me close this window and go to view source. interesting. it looks like there's somenew tags, among them script. so let's take a look within cs50ide exactly what i sent to the user. >> so here is-- let'sfocus on the html only.
here's the bottom half of dom-0.html. and notice that it's got a title,a head tag, a body tag, a form tag. but what jumps out to you asdifferent, especially if you've never written any javascript yourself. let me scroll a littleto the right here. i've got an input,another input for submit. i've got an id, which is kind of new. but we did see this with css. what else is definitely new?
nice. so where it says onsubmit,notice what seems to follow. this is an attributein html nomenclature. its value is this quoted string here. and this looks a littleweird at first glance. it's not html. it's not css. this is, as you might guess, javascript. so it seems that built into thisweb page is a function called greet.
and i'm inferring that justbecause it's a word, greet. it's got an open paren,close paren, semicolon. looks like a c function,looks like a php function. >> and indeed, it's going tobe a javascript function. then i'm returning false. we'll come back tothat in just a moment. but where is this function defined? well let me scroll upto the top of the file. and even though it's a long line,it's relatively straightforward.
let me zoom out here andfocus on these four lines. >> so in javascript, justlike php, you just say, literally, the word "function,"the name of the function, and then parentheses with anyarguments-- no arguments in this case. and there's no return typein javascript, just like php. so it's a little looser than c.open curly brace, close curly brace. built into javascript is a function--not a recommended function-- but a function called alertwhose sole purpose in life is to pull up that pretty uglyprompt that we saw a moment ago.
>> now this is kind of a mouthful. what's going on here? so let's start tohighlight everything here. that's the same argument to alert. and what's going on? this just looks like a string. and it turns out, unlike php and unlikec, it doesn't matter in javascript if you single quotes or double quotes. they'll be equivalent.
and frankly, it's justpopular these days for javascript programmers to alwaysuse single quotes for some reason. it's just the thing to do. but we could use double quotes, as well. >> so plus is a new character. but those of you who've donethis before, what does plus mean? yeah. concatenate. so we saw this in php.
there's just the dotoperator in php that will concatenate two strings together. c was a pain in the neck to do this. recall from pset six, which wasan especial pain in the neck, you would have to usesomething like strcat after allocating memoryon the stack or the heap. you had to jump through hoopsjust to concatenate two strings. in javascript, it's super simple. just use the plus operator between them.
>> so the complex-lookingthing seems to be this because at the end ofthis whole string, i just concatenate on an exclamation point. so if what was popping up was"hello, david," "hello, hannah," "hello, maria," and so forth, clearlythat middle thing in between the two pluses must give me access to what? what's in there for sure? so i'll pretending here theanswer their name, right? so their name popped up in the finalresult. so what does this mean?
well, i proposed earlier in thatpicture that the so-called dom has this special root elementway up top called document. and now, it turns out, that's goingto be a special global variable in javascript, built into which is awhole bunch of useful functionality. among the useful functionality is theability to get at any descendant node. those squares or rectangles or ellipsesare just nodes in a tree, so to speak. >> so it turns out that built intojavascript's document object is a function, otherwise known as amethod, that's called getelementbyid. the syntax for callinga function in javascript
that is inside of an object or avariable is just with the dot notation. and we saw this in cwhat the struct syntax. you see this in pset seven, kind of,sort of, when you see cs50::query. the colon colon in php is anotherway of calling a function that's inside of some object. >> but for now in javascript,it's just a dot. and so this function,nicely enough, kind of says what it does-- get element by id. an element is just another namefor a tag or node in the dom.
and so get element by id "name"means this-- here's my html. and based on this html, whatnode or what html tag am i going to programmatically be handedby calling document.getelementbyid? >> yeah, exactly. i'm going to get the inputelement there whose id is "name." so specifically, you canthink of this function, getelementbyid, as a way of givingback a pointer to that specific node in the tree. we haven't drawn thistree, but it's a way
of getting access to thatrectangle or that rectangle by uniquely identifying it via its id. >> now, why is this useful? well, it turns outthat once you've gotten that node, that rectangle from thepicture, that node inside of it, in turn, has a whole bunch ofproperties-- key-value pairs or data, one of which is called value. so literally, it's kind of amouthful to explain the whole thing. but at the end of the day,all this does is give you
a string that the user typed inin this hierarchical fashion. but i don't like acouple of these things. or rather, there's some curiosity still. all of that seemed to work. why do you think i returnedfalse after calling greet? this looks a little ugly, thati have two statements there separated by semicolons. take a guess. if i removed return false, whatmight happen, just instinctively?
sorry, say again? >> open a bunch of windows. so potentially maybe somethinglike that would happen. what else? might submit a request where? to the same page. so, in fact, that's thatthe closer answer here, even though, unlikein the past, i've not specified the action attribute,which normally we have to do.
turns out there's a default.if you don't specify action, it's like saying quote, unquoteor the name of the file itself, which in this case wouldbe like dom-0.html. it's just kind of inferred,or rather implied. >> and so if i don't do this, let's notice. let me save this. and i've removed return false. let me go back to thisexample and force reload it. and you might have seen me suggestthis on cs50 discuss a bunch of times.
if anything's ever acting funky and thebrowser's not behaving as you expect, oftentimes you'll want to holdshift and then click reload. that will force every file to reloadand not use your browser's local cache or copy so that now, let me go ahead andopen up my inspector, the network tab. i'm going to clickpreserve log because i don't want it to delete the rowsonce i get whisked away elsewhere. >> let me go ahead here andtype in andi, click submit. that seems as expected. it says "hello, andi."
let me click ok. notice that the page changed,albeit to the original page. notice the url kind of changed. it added a question mark,which is usually an indicator that we tried to submit something. and then at the bottom,even more explicitly, here is the actual http request,which got a response of 200 that brought me back here. >> so this is not whatwe want to do, right?
because i don't want toreload the whole page. i instead wanted to returnfalse so as to short circuit the browser's default behavior, whichwas, of course, to submit the page. >> so let's take a look at amarginally better example. this is dom version one. and notice the following. it's ok if you don't grokall of the lines of code. but what is fundamentally differentabout this implementation? i'll stipulate it behaves thesame, does the same thing.
what have i obviously done differently? >> audience: [inaudible]. david malan: yeah. so the function is defined differently--in other words, absent from the form, up there on line 7-- orrather, line 8-- no longer do i have the onsubmit attribute. in the previous example, i had this. and then i literally wrote my code here. and then i said return false.
and if it didn't rubyou the wrong way yet, it should start to insofaras, just like in html, when we started to co-mingle itwith css in style attributes, it just started to get a littlemessy or feel a little wrong. >> similarly here, ifyou start taking html, and then you automaticallyplop some javascript code in the middle of a quoted string, it'snot going to be very maintainable. it's not even obvious at firstplace where the javascript code is. so it would be really nice asa principle of better design,
let's keep our html completelyseparate from our javascript. >> so to do that, what we'vedone here is the following-- we simply use html for markup only. and so in version one of this, alli have is a form with a unique id. and then down here, i'm taking advantageof a special feature of javascript whereby i can have what'scalled an anonymous function. so it turns out that if i calldocument.getelementbyid of 'demo' that's like giving me a pointer tothis node in my tree, the form element, so to speak.
>> now, i just know fromknowing a bit of html now we're having read some onlinereference, that a form element supports a whole bunch of event listeners-- inother words, the laundry list of event listeners that we saw a moment ago. i know from reading the documentationthat onsubmit is a valid event listener for a form element. >> so once i know that,it's safe for me to do the following-- get that nodefrom the tree, the form element, and access its so-calledonsubmit property.
so the dot just meansthis is a property, like a special value inside of it. and what data type am iassigning, apparently, to onsubmit, which iseffectively a variable inside of that node in the tree? it's a field inside of that struct. what's the data type? >> a function, yeah. so it turns out that php has this.
and even though wedidn't tell you about it, c also has function pointers, theability to pass and assign functions as variables' values themselves. and we're not goingto regress back to c. but for now, it turns out thaton the right-hand side here, even though it looks a littlefunky, this means, hey browser, give me a function. i'm not going to even bother givingit a name because i'm literally going to assign let's call itthe address of this function
immediately to onsubmit. in other words, browser, you don't needto know what this function's called. you just need to knowwhere it is in memory. and so it suffices just tohave an equal sign there and not to bother naming this, likefoo or greet or any other word. and now this is just a stylistic thing. i could move this curly braceonto the-- sorry-- next line like we usually do cs50. but in javascript, it'sactually stylistically common
to just keep the curly brace, thefirst one, on that first line. >> but hereafter, there'snothing interesting. that open curly brace justdemarcates the start of my function. the function is nowidentical, except i've included the return falseinside of this function. because it turns out--and you would only know this from readingthe documentation-- that if the function that you assignto the onsubmit handler returns false, the browser just knows and agreesnot to submit the form to a server.
if it returns true, it will submitit to a server for reasons we'll see are useful in just a moment. >> and then the semicolon afterthe curly brace there just means i'm done defining the function. you know what to call as soonas you hear a submission. this is still arguably kind of ugly. so what more can we do? >> well, it turns out then inversion two, which is the last-- and we'll just glance at this.
at the risk of makingit uglier, it turns out that there's a library inthe world called jquery. and jquery is a superpopular javascript library that's so popular that mostany javascript-- it's not uncommon for people to confusejquery with javascript. javascript itself has veryverbose ways of doing things-- document.getelementbyid, dadadadadada. you end up having verylong lines of code. >> so a fellow named john resid,who actually works for a startup
up these days, came outwith this library years ago that many people have contributedto called jquery that changes the syntax in the following way. and just so you've seen this,because you'll invariably see this if doing aweb-based final project, this would be the equivalent way ofimplementing that same function using this special library. >> now, rather than teaseit apart in its entirety, let's just look at some patterns.
this syntax appears to havehow many anonymous functions or nameless functionsor aka lambda functions? two, right? and you know that, even ifyou're not super comfy with this, just by the fact that itsays function() twice. >> and it turns out thatwhat this code is doing-- and we'll refer to online references,ultimately, for some help with this. this just means that whenthe document is ready, go ahead and registerthe following function
as the submit handler for the htmlelement whose unique idea is demo. and then, when that happens,call these two lines of code. and this is, tragically, a moreverbose way of saying return false. and we mentioned this just becauseyou'll see code like this online. and it's nothing to be daunted by. but rather, keep in mind that what'sgoing to be common in javascript is this paradigm. and so that's why we show it for now. so without dwelling toomuch on that syntax,
are there are any questions onthese examples or ideas thus far? so let's use this for something useful. making a web page that just says hello,so and so isn't all that interesting, not to underwhelm. this one's not going to be beautiful,but it is going to do something useful. let me go back to my directoryhere and open up, say, form-0.html. >> so suppose this is the freshmanintramural sports registration page without any css or any sense of design. and i want to go ahead andregister here with a password.
and i'm going to agree to the termsand conditions and click register. and now the website says, "you areregistered! (well, not really.)" that seems like it worked, butlet me go ahead and force reload. >> and let me say, no, you don'tneed my actual email address. or maybe we'll just say mail in there. password will be, like, 12345. and then, just because i'man idiot, now it's 123456789. and i'm not going to check your box. >> hmm.
so there's several opportunitiesfor improvement here. and you know, or will see in psetseven, that you can write code-- and you'll have to writecode in php-- to defend against these kinds of usererrors because the user clearly has not cooperated. and he or she has not given you all thevalues you wanted or even in the format that you wanted them. so you'll see in pset seven thatwe could certainly have some if conditions that sayif the email address
isn't a username@something.edu,we could just say sorry and apologize to the usermuch, like you might be in pset seven. or if they haven't checked that box,turns out in php, you can detect that, too. and certainly if the passwordsdon't match as in register.php for pset seven, you can detect that. but that's a pain in theneck in that now they request us to go all the way to the server. the user is informed of the error.
and at least unless you usesome fancier techniques, now they have to click the back arrow. wouldn't it be nice, likea lot of websites today, if you had more immediatefeedback, instantly? >> in other words, let me go to versionone, which is going to be no prettier. but it does have this feature. malan, 12345, 123456789, notgoing to check the box, register. passwords do not match. so even though this pop-up is ugly--we can replace this eventually
with something like bootstrap,which you'll see in pset seven is a very popular library-- i diddetect that the passwords do not match. well, let me fix that as the user. let me go ahead and say 12345, 12345. still not checking the agreement. you must agree to theterms and conditions. so why? >> if we've already positedthat there's a way, and we've required you inpset seven to detect error
conditions like thisserver-side, why should i bother also doing this in javascript? what's an argument infavor of adding what you're about to see as some--there's additional complexity. >> maybe there is no upside. what could it be? audience: [inaudible]. david malan: oh, interesting. potential exploits.
so sure, if you're not handlingerroneous user input that great, maybe it's all the better if itdoesn't even reach your server. i would push back there andsay, you should probably fix both of those problems. but that's fair. >> david malan: yeah. this code, as we said before, isinterpreted on the client-side. it doesn't bother the server,which means it doesn't impact the server's load or capacity.
and now, for little old me,this has no meaningful effect because i have one user right now. >> but if you're anywebsite of decent size, especially the biggest, like facebook,the more you can keep people off of your server the betterbecause a server, of course, only has a finite amount of ram,a finite number of gigahertz, a finite number of thingsit can do per unit of time. so if there are more people inthe world hitting your server, accidentally loggingincorrectly, just as well if you
can keep that load off your server. plus, especially on a mobiledevice-- if you've ever log into my.harvard oryale's netid or the like, there's this the latency with a lot ofwebsites like that whereby it takes, like, a damn second or two sometimes. and then, my god, if you mistype,then you have to hit back and redo it. so there's latency, especiallyon slower network connections. but javascript, becauseit runs on the client and doesn't need to go back and forthacross a potentially slow internet
connection, you can getnearly instantaneous feedback. >> so let's look at this. let me open up form-0 andlook at the html here. and let's just see what's going on. this is a form whoseaction is register.php. i'm just using get sothat i could see the url. but for passwords, we'd surely wantto change this to post in reality. here's an input field of type text. here's another inputfield of type password.
here is, if you've never seen,an input of type checkbox. >> but there's no javascripthere whatsoever. this is just html thatgoes to register.php. but in version one, where istarted to get those pop-ups, let's see what actually happens here. in version one, whati'm going to see-- i thought i could stall enoughwith enough words, but i ran out. >> in version one-- there we go. in version one, notice the following--and is not the best implementation,
but it's my first. notice that below theform, i have a script tag. and a script tag means,hey, browser, here comes some code in,typically, javascript. and now, notice what i'm doing. on line-- i can barelyread it-- line 32, it says, var form-- so give mea variable called form. and then get document.getelementidof "registration." what is this?
well, let me rewind up here. and notice, ah, i gave the form elementan arbitrary but descriptive idea of registration. so this gives me a variable thatallows me to grab that node, that rectangle in the tree called form. form.onsubmit means, hey browser,register an event listener on this form. in other words, when this form issubmitted, execute the following code. it doesn't need a name becausewhy do you need to know the name?
you just need to knowwhat to execute, ergo it's an anonymous or lambda function. and that function isall of these lines here. and now, to be honest, even though youmight not have ever written javascript before, it's just c and php logic. so if form.email.value==" "--so if the email field is blank, yell at the user with "you mustprovide your email address." else if form.password.valueis blank yell at the user, "you must provide your password."
>> more interestingly logically,if form.password.value does not equal form.confirmation.value--where did confirmation come from? let me rewind. well, i called this inputfield here password. and i called this one here confirmation. i could have called itpassword two or anything else. i'm just logically checkingthat these two are the same. else-- it turns out this is mr. booleagain-- a boolean value, the check box. so if i say, exclamation point--if not form.agreement.checked,
yell at the user as well. >> so this syntax you'll see isvery common in javascript, where you have this dotted notation. you start with an object here. you dive in deeper to a toa property like password. and then you get at its actual value. and again, here is the input. here is the name password. and its value is whatever thehuman has actually typed in.
>> so in all of thesecases, i returned false. but if not, i return true. and so now we see acompelling use of when you would return false tostop what the user's doing and make him or her chooseagain or type again. otherwise, we return true. >> and let me introduce oneother variant of this just to seed some understanding thereof. well, in version 2 of this, form-2--i'll do it with a wave of a hand.
this is, for those curious,the jquery version, those of you who might want todabble in that particular library. but let's start-- and any questions? let me pause for moment becausethat was fast and a lot. >> but the nice thing here is that allof the code is pretty much the same. the new stuff is what is the dom? what are these rectangles? what are these nodes? what's an anonymous function?
what's an event handler? but thankfully, most of that is justfull circle from, say, week zero. so something slightly more interesting? well, first of all, let me goahead and open up google maps. and you'll notice that for amoment, on the split second, notice what happens wheni click fast enough. and this connection at harvard is sofast that you don't really notice it. but what do you kind of sort of seeif i click and drag really fast? those of you watching online,if you slow this to 0.5x speed,
you can see this better. >> what was happening justbefore i clicked and dragged? let me try here-- let me dosomething else, like 90210. let's go far away. that was really fast, too. how about disney world? there we go. ok. what did you see for a split second?
just, like, squares, right? placeholders for tiles? >> well, what's going on here? google maps is a nice example ofthis technology that's called ajax. and this is where we'll start touse the javascript in a particularly alluring way. back in the day, there wasthis website called mapquest. and i should have taken ascreenshot of this from the 1990s, where if you wanted tolook up here on the map,
you would literally click an arrowup at the top that showed you a different square of the map. if you wanted to move left, youclicked an arrow that showed you and some websites still do this today. but even mapquest has gottenbetter, like google maps. >> instead, what's better thesedays is websites that use ajax. ajax-- otherwise known asasynchronous javascript and xml, which is just a fancy way of sayinga technology or technique that allows a browser using javascriptto make additional http requests
after the page has been loaded. so what does this mean? well, it would be kindof annoying in gmail if every time you wantedto check your mail, you had literally hit control-r orcommand-r or click the reload button and the whole darn page would reload. it would flash whiteprobably for second. you would see the stupid progress bar. and just to see if you have newmail, the whole web page and the url
you're at would have to reload. >> but that's not what happens in gmail. when you get a new email ingmail, what happens on the screen? it just shows up, right? it just magically appearsas a new row in the table. that actually involves adecent amount of complexity. in fact, if you think about this tree,which even though is a simple one here, gmail-- and i'd have to lookat the code to be sure-- probably has an html table or maybean unordered list that it renders
each of your inboxes emails as. >> and so if you imagine this thereis a tree in memory when you're using gmail that looks kind of sort oflike this, when google realizes, ooh, you have a new email, it doesn'twant to rebuild the whole tree. rather, it wants to find the node inthe tree that represents your inbox and just insert a new node. >> so very similar to pset five, where youhad to insert nodes into a hash table, similarly does google, viajavascript code that it has written, traverse this tree, figure out whereis that inbox part of the window,
and then insert a new row. and a new row just means oneor more new nodes in a tree. >> and so ajax is this techniquethat allows for exactly that. once you've visited a url,however crazy long it is, and once the page hasbeen loaded, you can still grab more data from theinternet-- whether it's an email or a tile of a map--grab it behind the scenes and then insert it into the pageso that the human doesn't really have to wait for it.
>> facebook messenger works the same way. any number of other websites--oh, actually, even this. i mean, this is, frankly, kind ofan annoying feature these days. if i start searching for cats-- thisis kind of a horrible user experience. it just starts searching for me. well what is it doing? the url hasn't really changedsince i started typing. but what's going across thewire-- ok, hmm interesting. what's going across thewire here just gets weirder.
>> ok. so let me go ahead and inspectelement and go to the network tab and try to make thistechnical and less about cats. as i type, literally, catsand-- what's happening per-- i'm not going to click that. so down here, what's happening everytime i type a character, apparently? like, low level? what's happening with each of thosecharacters i'm typing at my keyboard? >> david malan: exactly.
each of those characters isgoing to google, one at a time. they are building up a stringon their server that represents everything i've typed in thus far. and every time i typeanother character, they use their secret sauce of asearch algorithm and figure out, does he mean this cat pageor this cat page or the like? so in some sense, it provides me with abetter experience in that i don't even need to complete my thought. and indeed, it's a usefulthing, autocomplete in general.
if their algorithms are good enoughand if my searches are obvious enough, i don't have to type the whole word. they're going to tell me what itis i'm actually searching for. so what google calls instantsearch is just using ajax, using code that allows them to requestadditional content via a web browser behind the scenes using thisnew language, javascript. so we have a couple minutes left. and let me call up my buddycolton up onto the stage, since it seemedparticularly fun last time
to introduce a technologythat some of you have expressed an interestin for final projects. we thought it'd be fun to bringup a volunteer, though, today to show you an addition tothis that allows you-- yeah, i saw this hand first. come on up. very well done. good job. i'm going to project this onthe screen in just a moment.
what's your name for everyone? >> efa: i'm efa. >> david malan: etha? >> efa: efa. >> david malan: efa? >> efa: yeah. >> david malan: nice to see you. let me get this ready. come on over to themiddle with colton here.
what colton has in his handstoday is a remote control. so rather than just stand there in athree-dimensional world looking around as colton did, now efa canactually walk around by going up, down, left, and right like anintendo or xbox controller. efa: i'm going to fall off the stage. david malan: i willstand roughly over here. but that is a risk. so go ahead and put those on. let me go ahead andswitch to the screen here.
let me dim the lights. and colton, let mecome stand next to you. >> do you want to explain herewith the mic what we're doing? here you go. >> colton: sure. so right now we'reloading up the oculus, i guess operating-- not operatingsystem, but the main program, where you can access all the games andapps that are in your library. so right now, it should saytap the touchpad to begin.
touchpad's going to be on theright side of the headset. so go ahead and tap-- efa: oh, man. david malan: yeah, there you go. the quality efa is seeingis much higher quality. this is just the wi-fi here. colton: so what you'regoing to want to do is look towards the topright of the screen. yep, that game on the very top right.
and then when you're selectingit, tap the touchpad again. i think its dreadhalls. and then here is a-- here, letme hold your glasses for you. >> so i just gave him a controller. so now he can control the game. he can move around and stuff like that. so go ahead and look up to the top. you should see new game. so go ahead and you can do that.
now, you should be able to controlyourself with the controller, as well, as soon asthe game loads up here. this might be a little bit scary. >> efa: now you tell me. >> colton: all right. so confirm that you can move around. you can move around. perfect. so if you look down, you have a map.
map shows you where you are. you can look around the room. you can completely turn around. yeah, exactly. turn around. >> so look to your left. i think there's something you canpick up on a barrel in the room. >> efa: how do i get themap out of the way? colton: look up.
just look up. there you go. now go ahead and just turn around. so look farther to your left. keep moving left. keep looking left. keep going. >> efa: oh, that way. >> colton: yeah.
walk towards it with the controller. now it should say pick it up. pick it up. now, let's get out of this room. go ahead and walk to that door. so you're going to hold-- it sayshold the button to force it open. so go ahead and hold the button. yep, forcing it open. now we're walking out of the room.
so i'm going to leave the rest upto you and see what you find out. efa: i'm not going in the dark room. oh, wait. now i have to go down the dark hall? ok, i'm going back [inaudible]. colton: all right. some more items to pick up. looks like some coins. that's a lock pick.
so if you find a lockeddoor, you can use that. are you scared? >> efa: not yet. colton: ok. >> pretend-- yeah. just pretend you'reactually standing there. and if you turn around--you've got to get used to it. but it makes sense. david malan: and while efa continues toplay, since we could do this all day,
we can all tip-toe out here. but we do have two other pairs,if you'd like to come up and play. otherwise, we will seeyou next on wednesday. thank you to our volunteer today. [applause] >> [music - "seinfeld theme"] speaker 1: well, i'mputting a new pl mount on. i just changed the olpf-- >> speaker 2: so whatexactly are you doing?
>> speaker 1: well, each one of these--here, i'll show you this one in here. you can see it right here. >> speaker 3: i think i'm good with these. you want some more? >> speaker 4: no, i'm good. [inaudible]. >> speaker 3: no, [inaudible]. have some. speaker 1: different color. speaker 2: ok.
speaker 1: so ultimately what itdoes is it adjusts the color of--