R.J. AQUINO: Let's just get started. So this is Quiz 1. Here is some high-level information. The About page for the quiz is at this URL, no longer CS50.net, although that will still work. It's CS50.harvard.edu/quizzes/2013/1. It's the big About page, telling you where and when, namely next Wednesday in a bunch of rooms. And by next Wednesday, I mean two days from now. All this information is there. But it is cumulative. So everything from the first half of the year is potentially on the quiz, because you can't really do advanced things in C without if conditions and for loops and the like. But there will be an emphasis on the material covered since Quiz 0, starting with structs and File I/O. It's typically more challenging than Quiz 0. The average score is typically lower. Study hard. While you're studying, be sure to use CS50/discuss to post your questions and read other people's questions. So if you don't have any questions, log in and read your friends' questions. They're probably good questions. And take the practice quizzes. We've been giving quizzes for seven or eight years now. They're all online. Future questions are similar to old questions. That's how we make them. The quiz doesn't exist yet. None of us have seen it. But it will look like previous quizzes. For this review session, this is not an exhaustive list of topics. You can't just attend this and then be perfectly ready for the quiz. Otherwise, it wouldn't be that much of a quiz. And this is also not necessarily everything you need to know about any given topic. It's meant to expose you to the things we've covered, remind you what we covered, and the way in which we covered it. But you will have to go further and deeper when you study to double-check that you know everything about any given topic and that you've filled in all the corners that were covered in lecture. The quiz notes tell you to go to the scribe notes, watch lecture videos. That's a good way to make sure you've covered all your bases. So getting started, when I made these slides, I tried to put where I found information. So for File I/O, for instance, Week 7, Monday's lecture, and the posted Section 6 and Problem Set all have information about File I/O. I've done this for every topic. So those title slides may be helpful to you. So here we have File I/O. Remember, in Problem Set 5, we used fopen, fclose, fwrite, fread, and fseek. Having recovered 30ish JPEGs and having resized and messed with bitmaps, you should be pretty familiar with these functions and how they work. If you are no longer familiar, definitely review them. And make sure you understand what the different arguments are, when they're used. But the common file-related bugs you may be asked about-- well, if you've forgotten to check if fopen actually worked before you go to modify a file. That could be bad. If you've forgotten to fclose a file that you've fopened, that's similar to a memory leak. That's pretty bad. And forgetting to check if you've reached the end of the file before you start writing to it. So if you say, hey, I'm at the end of the file. Give me 5 more bytes. Well, that's probably not going to work out the way you expect. That's really it for File I/O, because we did so much of it with the problem set. So if you understood what was going on in Problem Set 5, remember the bitmats and the JPEGs, then you're probably all set for File I/O. If that's a bit fuzzy, definitely review that problem set and the associated material. Structs were the topic that were on the line between Quiz 0 and Quiz 1. Didn't quite make the cut for Quiz 0. So they'll definitely be on Quiz 1, Week 7, Monday. What is a struct? Here we show a struct. It's like a new type. It's like a container for multiple fields. In this case, we've declared a struct student that has two fields-- a string that we're calling name and an int that we're calling age. So when I pass around students or I modify students, I'll be able to access their name and their age. Let's look at some code for that. Here we see that I've declared a student s, just like I declare any variable-- int x, int y, et cetera. Here's student s. He starts with nothing in his fields. So let's set them. You set fields of a struct with dot. So I've said here that s.name = RJ. And s.age = 21. You can also update fields the same way you'd update the value of a variable. So I want to change my name from RJ with no periods to R.J. spelled the correct way. It would be s.name = RJ, the same as we said it originally. And then you can access them. So we've set them. We've updated them. You can also access them in the very same way. So here, I'm printing out R.J. Is 21 years old. And I'm accessing those values with s.name and s.age. So that's accessing structs with the dot notation. Yep, question? AUDIENCE: Is there a reason on the previous slide that you didn't put student on the top line, like typedef struct student and then student at the end? R.J. AQUINO: So the question was, on this slide, we've typically seen typedef struct node and then the fields of the struct and then the word node. And how come here I didn't say, typedef struct student and then the fields of the struct and then student? The reason is that I don't need to access it inside of the struct. So it's OK to leave it without a name. I can just leave it as an anonymous struct. The reason we do it for linked lists and things is because inside you need to reference a struct nodes star. So the struct has to have a name, so you can access it later. It's a minor detail. But you'll typically see typedef struct curly braces if you don't need the name and typedef struct some name followed by curly braces if you will need the name. So that's a good question. And on that point, we tend to modify structs and pass around structs by reference, not by value. So we'll just pass around pointers to structs instead of passing around the structs themselves. So you're very frequently going to be using, in this case, student* or struct node* or node* instead out students or nodes. So here, I've said, OK, the variable ptr is going to be the address of s. It's going to be the pointer to the student R.J. So we can get at those fields the same as we get anything. First, ID reference the pointer to get the struct. That's *ptr and then a dot and then age. So to access the field, and I've updated it now to 22, because, let's say, it was my birthday. There's a shortcut syntax using the arrow here. So ptr arrow age is just the same as *ptr.age. Now, that's something you'll have to memorize and remember. You used it a lot in pset6, the speller pset. But this is actually what's going on underneath the hood. It's dereferencing the pointer and then accessing it. Question? AUDIENCE: [INAUDIBLE]. R.J. AQUINO: So why are we using pointers as structs instead of the structs themselves? The reason would be if you're passing a struct to a function, you probably want to pass around just the 4 or so bytes that represent the pointer, as opposed to the potentially 30 or 40 bytes that are the struct. So passing something to a function is easier when the thing is smaller in short. Question? AUDIENCE: You might have mentioned this in the beginning, but are there other slides up on [INAUDIBLE]? R.J. AQUINO: These slides will be up after the review session. We'll post them on the website. So moving on and moving on slightly faster, we're going to talk about data structures. There are a lot. We covered a bunch of them. Here's what you should understand about data structure. You should really understand at a high level what each structure is. Can you explain in English to your friend that hasn't taken CS50 how we're organizing our data and why we'd be using something in this way? That's thing one. Thing two, understand the implementation. So understand how to use these things in C. And we'll be going over this. And then thing three would be know the run times and the limitations of the various structures you're using. So understand why you would use a hash table instead of an array. Understand how fast, on average, accessing a hash table is. Understand what operations are fast on linked list but slow on arrays and vice versa. So to understand that, you'll have to understand Big-O notation just to know how to talk about these sorts of things. And we'll talk about that. So first thing, linked lists. Here is a high-level picture of a linked list. We show this in class. We typically have 10 people standing on the stage. But we have a series of nodes where each node has some value and a pointer to its next value. So to get from one node to the next, you just say, give me the next node. You have that node. Give me the next node. You have that node. Give me the next node and so on until there's no node left. So continue to talk about it at a high level. It's very easy to insert things into a linked list. If you don't care about the order, you can just drop it right at the beginning. That's constant time. But it's hard to find a value. If you're trying to ask, is seven in my list? You have to go through every single value. Is this seven? Is this seven? Is this seven? Is this seven? Over and over again. And that's O(n). So when studying for the quiz, compare this with arrays. Is that OK? The lights went dim. OK. When is a linked list better? When is an array better? So let's look at some code. Here is a potential node. It's a struct. It has an int n, which will be our value. And it has a struct node* next, which is our pointer to the next node. So here, we can see that we happened to have put an int in our node. But if this were a linked list of char stars or a linked list of floats, we totally could do that too. Remember in pset6, you probably had a linked list of char stars or just static char arrays. Let's look here at an operation. So we want to insert a new n into our linked list. We start out with a head pointer that is a pointer to this node that has the value of n and a next of a pointer that points to this node is a value of n and a next of null, because it's the last node. So in the interest of time, I will put all the code on the screen. And we'll walk through it a few lines at a time. So here's the code. I hope it's readable. The first thing we do is we malloc a new node. So it makes a pointer to a new node that doesn't quite have anything set up in it yet. We check to make sure that the new node isn't null. Otherwise, we have to give up. So having checked that, we now set the values in the node. So we put the new n into our n field. And we set the next pointer to point to the original head, so that we can now have inserted this node into our list. Finally, we have the global head point to our new node, so that if we were to start at head, we would be at this new first node instead of the old first node. And when this function exits, the variable new node no longer exists, because it was local to the function. So this is the state of the world. Our global head points to our new first node, which points to our original first node, which points to the node after that. That was insertion. I hope that was relatively straightforward to follow. When in doubt, draw a picture. So I find that talking about linked lists and looking at code is very not helpful. Whereas looking at a picture of a linked list allows me to think, oh, so I have this node here. But if I update that pointer, it ends up disconnected. And I've forgotten where the node goes. And the code exits. And you have multiple nodes that are disconnected. And you don't end up with the list you want. So if you draw the picture and do it step by step, hopefully, you'll see the correct order of things in terms of updating the pointers to make sure that the list comes together. Insert is relatively straightforward. A more complicated one would be insertion into a sorted list. A more complicated function is delete and find, so looking through a list to see if something is there. Perhaps you did this in pset6 when you got into your hash table and you said, well, is the word apple in my linked list? So you may have already done this. But definitely, refresh your memory and try to reimplement find and reimplement delete for a linked list. Fun side note, there also doubly-linked lists, where you have pointers that point both forward and backward, so that you could go to the next node and to the previous node. And there was a question on last year's quiz of that type, talking about doubly-linked lists. Now, that's a structure that you're relatively familiar with, because most of you probably used them on pset6. Here's one that's a bit less familiar. As a side note, I think that Quiz 1 is primarily harder than Quiz 0, because the stuff you're doing, you have not done as much. To put that another way, for Quiz 0, you had written a lot of C. And we asked you about C. For Quiz 1, we're going to ask you about PHP and JavaScript, which you haven't written as much of. We're going to ask you about C-code that you haven't written as much of, this advanced C stuff. So definitely, practice the stuff we talked about in lecture that you didn't necessarily do on the problem set. Speaking of which, you haven't written a stack on a problem set. But it was in lecture. Here's the high-level picture of stacks that we show every year. It's the stack of trays in the Mather dining hall. At a high level, stacks are a last in, first out data structure. That means you're going to put things in-- 1, 3, 7, 12, 14, negative 0. The one thing I couldn't have said-- negative 3, 0. You put all these things in. And the last one you put in is the first one that's going to come out. So you have two operations-- push and pop. All of the putting in that I was gesturing like this are push. And then when I reach in to grab something or reach on top to grab something, that's pop. So we're going to implement stacks. And we showed them in lecture using arrays. But you could do them using linked lists. A stack is a conceptual data structure, not like an implementation-specific one. So what would that look like? It would look kind of like this. You'd have an integer size. And you'd have an array of values that we're calling trays, because that's what the picture was for us-- int trays-- and then some maximum capacity. So what would push look like? Well, if we have a stack s, then to push something onto s, we would get the size of s. And that would be the next open spot of our array. So if we have three things in our stack, then trays 3 would be the next open spot, because 0, 1, and 2 are already filled up. So we put the value into s.trays[s.size], the third spot. And then we increment s.size to say, hey, we had three things before. Now, we have four. So the next time you push, you're going to put something into 4. Or the next time you pop, you're going to look at 3 instead of 4 or whatever. And then we'll return true to say, hey, we succeeded. This worked. As a rule of thumb, if a function that's supposed to return true or false always returns true, you may have done something wrong. So does this work? Well, it works fine for 1, and 2, and 3, and 4, and five. But let's say I reach my capacity. I've then run into a problem, because if size is the same as capacity, I'm now trying to put something into an array where I don't have space. So a short check to fix this. If s.size == CAPACITY, return false. Otherwise, go and do what we did. So what else could we ask about for stacks? What else should you study? What else should you practice? Well, implementing pop. We already did push. I'll fix that. A non-array implementation, where you use a linked list, perhaps. A non-int implementation. We did ints here. But it could have been floats. I could have been strings. It could have been char stars. Look at past quizzes for the kinds of questions we've asked about stacks. I'll say that we covered stacks around the same as we've covered them in years past. So the quiz questions should be a good indication. Moving forward even faster, queues. They're like stacks. But they're first in, first out. If you're British, the word queue probably made a lot of sense to you. Otherwise, you may have heard of it as a line. They work like the line at the Apple store. The first person to show up at 3:00 in the morning is the first person to buy his iPad. So we have two operations-- enqueue and dequeue. Enqueue puts someone in the line. Dequeue pulls the first person off the line. Again, we can implement this with an array. So what is the struct we showed in lecture? It was this one. Again, numbers. Again, size and this new thing front. Why is there something called front? It's the index of the next element to dequeue. It's just internally keeping track of the first guy to show up, so that we can pull it out when we need to. Definitely look at lecture notes and try to implement enqueue and dequeue when studying for the quiz. Important things to think about. Wrapping around if the front plus the size ends up bigger than capacity. Again, if your structure is full, you're going to have a problem. Hash tables you've seen before. Most of you probably implemented these on pset6. It's a structure that aims for O(1) constant time insertion and O(1) constant time lookup. In CS50, we implemented this as an array of linked lists. The key component to a hash table is the hash function. So it converts your input, let's say, a dictionary word, into a number, which is going to be our index. And we'll use that index into our array. So here's a cute little picture from study.50.net. We throw all the words into our hash function. And the hash function tells us where to put these words. This is all great in the land where there's only one word for every slot. But as you remember from pset6, there are more words than slots. So what happens when you get a collision? Instead of storing one value in, let's say, hash table 3, you store a linked list. And so instead of having cantaloupe here, you would have a linked list, where the first node is cantaloupe. And the next node is cat. And the third node is collision, let's say, because all these words start with C. So most of you did this for pset6. If you did not do a hash table on pset6 and you attempted something like a trie, definitely review hash tables. If you did do it on pset6, definitely review hash tables. And if you did it on pset6 and it didn't work out quite right and you had a lot of trouble with it, definitely review hash tables. So the lesson really is definitely review hash tables. The vast minority of you tried out tries on pset6. High-level picture. It's something like this, where each node has a set of children, where each child corresponds to a letter. And every node also says, hey, I am a word. So in this instance, the word Maxwell, if you follow the M to the A to the X-W-E-L-L and then follow it one more. And you get this symbol, delta, which we signify to mean this is a word. So Maxwell is a word. These deltas are throughout signifying which things are words and which things are not. So in pset6, the data we stored alongside any of our nodes was "I am a word." And the cool thing about tries is they demonstrate insertion and lookup in O(length of a word). So just to get through Maxwell, it's M-A-X-W-E-L-L. So seven or eight-- I can't count-- steps to get to the end and check things out. So quick implementation here. Rob went through a linked list in his postmortem. So check that out. Sorry. Went through a trie in his postmortem. So check that out. But you basically have each node has 27 pointers to the next nodes and one Boolean for am I a word. Check out Rob's postmortem for how this actually is implemented. Our final structure, our trees and binary search trees. So looking at these, these were covered most recently Week 8, Monday. A tree is similar to a trie, except you don't necessarily have 27 nodes at each point. And you don't have this data at each step that signifies whether the-- the path doesn't matter. Whereas a trie, the path from top to bottom, Maxwell, was important to us. But each node has multiple children, perhaps. We have some more vocabulary. The root of the tree is at the very top. And we say that the very bottommost nodes that have no children are leaves. So like a trie, a tree is a structure of nodes. A common type of tree that we're going to talk about is a binary tree, where each node has no children or one child or two children. So this picture here is not a binary tree, because node 3 has three children. But if we were to ignore those, the rest of it is a binary tree because it demonstrates the property that each node has zero, one, or two children. So how could we express this in code? We could have a node where each node has an integer inside of it, as well as a pointer to the tree on the left and a pointer to the tree on the right, so the two children. How is this useful? Well, if we make rules about where we put nodes, we can make search faster. So there's a concept of a binary search tree, where all nodes on the left subtree have a smaller value than the node we're looking at. And all nodes on the right subtree have a greater value than the root node. Now, that looks like a lot of words. I'm going to put it inside of double quotes and show you a picture. So here is an example of a binary search tree. See that we start with 10. Everything to the left of 10 is smaller than it. And everything to the right is bigger than it. But more so than that, each node in the tree expresses this property. So the node 7 has a 3 to the left and a 9 to the right. So all of those are smaller than 10. But looking at just those, the 7 has 3 to its left and 9 to its right. And similarly on the right, 15 has 14 to its left and 50 to its right. So the three nodes over there, 15, 14, and 50, are also a valid binary tree or a valid binary search tree. And they're all bigger than 10. So they are allowed to be on the right there. Is there a question? AUDIENCE: How do you deal when you have two sevens? R.J. AQUINO: Yeah. How do you deal with two values that are the same? Some binary search trees say that you ignore duplicates, because the goal is just to say, I've seen these things so far. Some binary search trees you could say have a count inside of the node. Others might say that everything to the left is less than or equal to. And everything to the right is greater than. It just depends on what the problem is you're solving. So in a dictionary, for instance, you wouldn't care about duplicates. You would throw them out. But some other problem you might care. AUDIENCE: Is it possible to have a 1 to the left of 15, which is less than 10? R.J. AQUINO: No. If the 14 here were a 1, this would not be a valid binary search tree, because everything to the right of 10 has to be bigger than it. And we'll see why. If in the land of search my goal is to find 14, I start at the root. So I look. OK. We're going to start at the root. Look at 10. Well, 14, our target, is bigger than 10. So it must be on the right. This is very similar to the whole phone book thing we did, the binary search there. But instead of binary searching in an array, we're binary searching in this tree. So we're still looking for 14. Well, 14 is smaller than 15. So if it's in our tree, it must be in this area here. It must be to the right of 10 and to the left of 15. And so we check this node. And yay, we've found 14. I'm not going to walk through it. But here's the code. It's actually relatively straightforward, because this is recursive. What could we ask you to do on a quiz? We could ask you to write this code. We could ask you to look at this code and modify this code and explain what it's doing. Yeah. Question? AUDIENCE: Are these slides going to be made available as they were last time? R.J. AQUINO: Yes. So these slides will definitely be posted. AUDIENCE: They're actually posted right now on the website. David just did that. R.J. AQUINO: The slides are right now on the website. I'll probably patch up a couple of the typos I noted and fix them. But there's a current version on the site. Others things we could ask you to do-- write insert. Write an iterative version of the recursive function we just showed you or talk about these things, like in paragraphs, in words, in sentences. Comparing the run times and explaining what you would want to use a binary search tree for instead of a hash table, for instance. So understand these structures at a pretty deep level. Understand how to write them, how to use them, how to talk about them. And you'll be all set. Question? AUDIENCE: When you're writing the binary search tree, how do you determine what value to make it as the root? R.J. AQUINO: So the question was, what value do you make as the root? Depending on your code, you may have a global root. So you may have likely had in pset6 a global hash table. Or you might pass the root in as an argument. So this search function here takes an argument a node*. And so whatever node you happen to be looking at is the one you're treating as your root when you pass it in. And I'm all set. Those are my slides. The next person can come swap in a laptop and mic. ROB BOWDEN: I think I might have interpreted that question differently. But I interpreted it as, if you have the numbers 1, 2, and 3, how do we know to make 2 the root as opposed to 1 or 3? If we make 2 the root, then it's nicely 1 and 3 to the left and right. But if 1 is the root, then it's 1 to the top, 2 the right, 3 to the right. So by default, you don't know what to make the root. And for any algorithm we're expecting to give you, just the first thing you insert would be the root. Or we'd give you a binary tree that already exists that has a root. But other algorithms exists such that the root will update, so that if you end up in the situation where it's 1, 2, 3, it would automatically update to make 2 the new root, so that it's still nicely balanced. ANGELA LI: Cool. Hey, guys. I'm Angela. And I'm going to finish off our C and then go into some of our web technologies-- HTTP, HTML, and CSS. So the first thing is buffer overflow attacks. So let's take a look at this code. It's pretty simple. There's a function foo. And it doesn't return anything. But it takes in a pointer to a string called bar. And it's going to declare this buffer, which is a character array that has 12 slots. And it uses memcpy, which is just a function that copies from one address into another. So this is trying to copy into our buffer from whatever bar is pointing to. So any idea what's wrong with this code? AUDIENCE: If bar is longer than C, they will overwrite. ANGELA LI: Yeah, exactly. We have no guarantee that bar is going to be less than 12. We just made some arbitrary number 12. And we were like, let's hope that our user input is less than 12 characters long. So in an ideal world, if our input is always as expected, then we'll get something like, hello. That's less than 12 characters. It gets read into char c. And then we do something with it. It doesn't really matter. But a malicious person could do something more like this, where they give us whatever bar is pointing to, it's going to point to this huge array of just A's. And this is way longer than 12. So it's going to go all the way down here to where the return address used to be. So let's say this function is called foo. Maybe foo was called by some other function, which was called by main. So when foo is running, it needs to know where to return to. If foo was called by some function named baz, it has to know that it's got to go back to baz. And that's what this return address down here is telling us. But if we overwrite it with some other address, in this case, this is a representation of the address at the very beginning of this buffer, then what's actually going to happen is that instead of returning back to baz, which called our function, it's just going to go to the front of this code. And if this was there because a malicious hacker dude came and injected this, then maybe this amount of A's is not actually A's. And it's actually just code that breaks your computer or something. So to be defensive about this sort of thing, you have to never assume that user input is a certain amount of characters. For example, when you were doing speller, you were told that words were only going to be 40 characters long maximum. And that was good. But if not, then you would have to make sure to only read in 45 characters at a time. Otherwise, you might overwrite your buffer. Any questions on that. Yeah. AUDIENCE: Could you just talk a little more about these? ANGELA LI: Sorry. Yes. AUDIENCE: The mic is just for video. I will try and project. Hi, guys. Sup? So let's go over a few things in the CS50 library, which you've been using all semester, mostly to get user input. As you know, you include the CS50 library by just doing CS50.h, which contains all the prototypes of the functions that you can use, like GetString and GetInt, and GetFloat, et cetera. And there's this one line in the CS50 library which defines a string, which you guys all know by now is just a char*. But let's take a peek at how GetString works. This is a very abridged version. You can pull up the CS50 library files from, I think, manuals.CS50.net. And you can read through the actual function. But this covers some of the important parts. So we've created some buffer with some capacity. And what we do is we get one character at a time from standard n. That's where the user inputs text in the console. And so we're going to read in a character so long as it's not a new line and it's not end of file, which is the end of standard input. And for every character that we read in, if that character ends up adding to the number of characters we've read in and that is more than our capacity, then what we do is we just resize our buffer so that it's twice as long. So again, this protect against buffer overflow attacks, because you read in a character at a time. And if at any point you read in too many, you just expand your buffer. You multiply it by two. And then you have more room. Otherwise, you just add a character to buffer. And after you've read in all the characters, it will shrink the buffer back down to the normal size, add a null terminator, and then return. Now, let's look at GetInt. Can you guys read this? I can zoom in a bit. I don't know how computers work. Never mind. I can't zoom in properly. This is really hard. I'm sorry. Let's just look at this. So what GetInt does is it first reads in a string from GetString, which we've implemented before. And the important part to note here is if this sharing that it ends up reading is like not actually a string, then we just return INT_MAX to represent failure. Why do we return INT_MAX instead of negative 1 or 1? Any ideas? AUDIENCE: [INAUDIBLE] negative 1 on one. ANGELA LI: Yeah, exactly. So you're way more likely to just want to input 1 or negative 1 when prompted for an nth and whatever nth maxes. It's huge. You're probably not going to use it. So this is like a design decision to make sure that you don't accidentally return an error or you don't return 1, which might be parsed as a correct answer. So if a line doesn't exist, we return INT-MAX. Otherwise, we use sscanf, which is like scanf. But it reads from a string. And we have this formatted string, which is %i %c. And we try and match that with whatever the user gave us. We want the number of matched things to be 1, which means that we only really want to match an integer surrounded by maybe white space, maybe not. In this case, if you put in something like bar, bar doesn't match at all, because there needs to be an integer at the start. So sscan never turned 0. So you don't return that. Alternatively, if you put in something like 1, 2, 3, A, B, C, that matches both the integer but also the character after it. So sscanf will return 2, which is also not ideal. You don't want 1, 2, 3, A, B, C to be a valid int. So that also doesn't work. But say you put in something like 50. That will match the %i, which means it will get read into n. And now, n will contain the number 50. And then you can return it. Otherwise, you hit Retry. And then it just goes over again until you get a proper input from the user. Any questions on that? AUDIENCE: So if you were to print out the value of the GetInt on [INAUDIBLE] would it be just the integer and max? ANGELA LI: Yeah. So if you use GetInt, you should assume that you don't want nth max to be a valid input, because you're going to assume that that was bad. AUDIENCE: If we didn't have char c and someone put in 1, 2, 3, Sam, would it still work for 1, 2, 3? ANGELA LI: I think it would work. But you don't want 123Sam to be a valid input by a user. That's not really an int. So it doesn't seem fair to parse it as an int. OK. In that case, let's move on to the internet. So HTTP is not a language. HTTP is just the set of standards for how you send things from clients, that's you, to servers. That's other people on the web. So HTTP stands for Hypertext Transfer Protocol. It's the heart and soul of the whole web. The hypertext part just refers to HTML. The transfer is clients like you will send requests to servers, which give responses. And the protocol is just, how do you expect a server to behave? And how are you supposed to behave such that you can streamline this communication process? So HTTP requests look a lot like this. GET is the type of request. You guys have seen GET requests and POST requests. That second thing there, /me, that's just the URI or the URL of where you want to go within the host. So this request is asking for the page, like www.facebook.com/me. And it's a GET request. And then this HTTP/1.1, that's just the version of HTTP you're using. It's almost always 1.1. And then there's a bunch of other stuff too. You can actually see these if you open up your console when you're browsing the web. Responses look something more like this. The top part is, again, the type of HTTP you're using followed by a status code. So 200 OK is everything worked out. Here is your content. Your content is going to follow. And then it will tell you what kind of content and other stuff too. The status codes, there are a few important ones that you should know. 200 OK is like everything's golden. Everything works. 403 Forbidden. This you've probably seen if you forgot to chmod something properly. It means that you don't have the right permissions to access that on the server. It's like, no, you can't see it. 404 means that thing doesn't exist. Not found. You've probably seen that a lot. 500 Internal Server Error is usually like something went wrong on the side of the server. So when you were implementing pset7, if you had PHP errors, you could actually go to the page and see a whole bunch of PHP error stuff. But that doesn't normally happen, because websites don't really want to tell you why their site is broken. They'll probably just return a 500 Internal Server Error. And then there's 418 I'm a teapot. There's a whole story about why that's a thing. But you can read about that on your own time. There's a whole bunch of other status codes too. But these are the ones you should know. So let's talk about HTML. HTML, remember, is not a programming language. It's a markup language. That means it describes content. It tells you what an HTML document looks like or not what it looks like but how it's structured. So it defines a structure and semantics of web pages. It's like, this is a paragraph. This is an ordered list. This is like a section of my page. Here's the title. It does stuff like that. It doesn't style any of that, because that's what you do in CSS. And it looks like a series of nested tags. So to use an example of a really basic HTML page, you have the DOCTYPE declaration up there. This DOCTYPE declaration is saying, we're using HTML5. Then you have the big HTML tag. It contains a head and a body. Inside the head, you have the title. That's what goes in the title bar of your browser. We have a link tag that links in an external style sheet. And then we have a script that pulls from an external JavaScript as well. And then inside our body is actually what gets shown on the page. We've got a paragraph and then an image inside that paragraph. This one is a picture of kittens. Notice that the image tag closes itself. So instead of opening with an image and then doing another /image, you just have this little slash here, which closes it. And the image tag also has this key value attribute called alt. That's the alternative text that happens when you hover over it. Most HTML elements have some key value things that you can give it, various customization. Yeah. AUDIENCE: [INAUDIBLE]. ANGELA LI: Well, so it's an attribute of the tag. So if you were using jQuery, you could do select image.getAttribute. And then you can search for get the alt attribute. And it will give you kittens. If you remember forms in HTML, input elements will have name attributes. And that's what PHP uses to send requests when a form is submitted. AUDIENCE: Did you mention something about how if you use kittens.jpg or something that has the missing file folders or other files? ANGELA LI: Yes. So this is what's called a relative path, because I'm not giving you the full path. This is like when in C if you do fopen some file, if you fopen hi.txt, that hi.txt is expected to be in the same directory, unless you give it a more complex path. AUDIENCE: So you could specify which folder [INAUDIBLE]? ANGELA LI: Yeah. And you can look up how to do that. But if I wanted to get kittens.jpg out of the parent directory, I would do ../kittens.jpg. Yeah. Sorry. Yeah. Oh man, I forgot the question. What was the question? Oh, the question was is, kittens.jpg expected to be in the same directory? And in this case, it is. But you can also give it a certain path such that it doesn't have to be. Good? CSS. So CSS, like HTML, is not a programming language. CSS is just a series of styling rules. It stands for Cascading Style Sheets. And you use it in conjunction with HTML to style pages. So there are three ways you can include it. One way you can do it is in the head portion of your HTML, you can just open a style tag and then stick some CSS rules in there. It's pretty OK. Yeah. AUDIENCE: Could you put those style tags in between, let's say, body and /body. And then you would be styling only in body. ANGELA LI: You could. It'll work. But you shouldn't, because styling is kind of the metadata that should go in the head of your document. Body should really only contain what's actually going to show up on your page. AUDIENCE: So you'd put style in your head to style the entire web page, right? ANGELA LI: Yeah. So putting style here, these CSS rules will apply to the whole page based on their selectors. So the better way to do it is instead of having a style tag in your head, you have this link to an external style sheet like I showed you in the previous example. What this does is it tries and finds the file style.css and then pulls it in and uses that as the styles for the page. And your style.css would just look like this. It would just be a bunch of CSS. And finally, there's another way you can include CSS, which you really shouldn't ever do. It's call inline styling. And so any HTML element can also take a style attribute. And then in that style attribute, you can give it CSS rules. So in this case, whatever div I'm defining right here, it's going to have a black background and a white text color. But you shouldn't do this, because what this does is it puts your styling inside your HTML. And I know we've been talking about HTML is structure and CSS is style. If you do this, it mixes them together. And it's not very clean. So don't do that. Using an example of CSS, up there, we just select the body of the HTML documentary. And we're like, everything's going to be Comic Sans. I also don't recommend that. But you could do that. The second rule right here, it's going to select the element on the page with ID main. So whatever HTML element, I said ID = main, I'm going to give that a 20-pixel margin and align everything, all the text, to the center. The last thing selects by CSS class. So any element on the page that I gave a section class, I'm going to make it a background color of light blue. Yep. That's all I got. Question? AUDIENCE: What does the hashtag before main do? ANGELA LI: The question is, what does the hashtag before main do? In this case, the hash in CSS means select by ID. So if I had some HTML element, like divID = main, this CSS rule selects the thing with ID main. And similarly, the period in front of section is select by CSS class or select by HTML class. AUDIENCE: Why is there a has before 6 in background color? ANGELA LI: Yeah. So the question is, why is there a hash before the 6? This is different than that hash. This means that you're giving a hexadecimal color. So hex colors, this just represents a color. And you remember RGB triples when you did the forensics pset? This is similar. The first two digits represent how much red is in the color. The second two represent how much green. And the third represents how much blue. And the hash is this is going to represent a color. So anything from 0, 0, 0, 0, 0, 0 up to F, F, F, F, F, F is valid. It's some valid color that can be displayed by your browser. Question? AUDIENCE: What's the difference between using by ID and by class? ANGELA LI: The question is what's the difference between using by ID and class? You can only have one element in an HTML document that has a given ID. So only one thing on my page is allowed to have ID main. So you use it for this is the header. This is the navigation. This is the footer. Classes are different, because you can apply classes to as many HTML elements as you want. So for example, I did class section, because there's probably more than one section on my page. You're just allowed to have as many elements on the page with the same class but only one with a certain ID. AUDIENCE: So the dot represents the class? ANGELA LI: Yeah. A dot represents a class. Cool. That's all I've got, guys. Thank you. [APPLAUSE] ZAMYLA CHAN: Hi, everyone. I'm Zamyla. I'm going to be covering PHP, MVC, and SQL today. A lot of the material that I'll be covering is going to be pretty much right out of pset7. All right. So what is PHP? PHP stands for PHP Hypertext Preprocessor. So it, in itself, is a recursive name, which is pretty cool. PHP is a server-side scripting language, and it provides the backend and the logical underpinnings of our website. So Angela talked a lot about the HTML and CSS that will make the structure of the website. But what if you want to change that content dynamically or if it varies based on the user or certain conditions? That's where PHP comes in. Now, typically, PHP might take a few less lines to implement the same thing in C. That's because PHP handles memory management for the programmer, as opposed to us having to malloc free, things like that. But since PHP is an interpretive language, typically, it might execute a bit more slowly than C, which is a compiled language. Because we're moving programming languages, let's look at how the syntax will differ. Let's be very careful not to get confused with this. So with PHP syntax, whether you are embedding your PHP inside of an HTML file or within a .php file itself, you need to enclose the code in the open PHP and the closed PHP tags like follows, like on the screen. Variables in PHP. Every single variable will start with the $ sign followed by the name of your variable. Now, variables in PHP are loosely typed, which means that you don't need to indicate what the data type is when you're declaring it. However, this doesn't mean that they don't have any types at all. So if I declare a variable and just set it equal to 1, and then I declare another variable, set it equal to "1," and then another one 1.0, well, depending on the type of equality operators I use, if I want to compare across all types, then they'll be equal. But if I want to make sure that the types are equal, PHP can still do that, even though we don't indicate what type it is when we first make the file. Now, in PHP, even though we are switching over from programming languages from C, we still have our trusty if condition, just like this. We still have our while loops, just like this, where you put in your condition and then the body of the loop. And then we also have our for loop, which typically looks like this. So if I wanted to iterate over all nine psets and submit and call a function submitPset, then I can do that here, which you guys have all done by this point. Congratulations, by the way. For the camera, people said, thank you. Now, if you didn't want to just use this for loop, then PHP actually also has things called foreach loops. So if I had an array of integers, 0 through 8, stored in the array psets, then I could have a foreach loop that iterates over every number in psets. And then I could call the same function eight times, just like I did before. So this for each loop is nice, because you don't have to if you don't know the exact length of the array that you have, then using this foreach loop will take care of that for you. So I made psets as an array. Let's look at that. Arrays in PHP are typically the same as the ones that we've had in C, where you can declare an array. And here, I can declare an empty array and then build up dynamically by using indices as integers. So index 0, I'm going to store an integer named 1. At index 1 of my list, I'm going to store the value 2. And at the third index but the second number, I'm going to store the number 12. Now, this is fine in that works it works well. But say it matters to me what each index holds. For me, index 0 means how many cats I have. And the index 1 means how many owls I have. And the next one means how many dogs. Well, then it to specify that, instead of having to remember 0 relates to cats and 1 to owls, I can use associative arrays, which means that instead of integers as my indices, I can actually use strings. So this is quite useful. And you've basically just replaced the integers with strings. And there you have an associative array. Yeah. AUDIENCE: Is there a reason why there's an underscore for the second part, because my list has the array. ZAMYLA CHAN: The question was, is there a reason why there's an underscore between my and list? No. That's just how I'm naming my variable. AUDIENCE: On the first line, it's one word. ZAMYLA CHAN: My apologies. I'll fix that. Yeah. They should be the same variable name. Good catch. OK. So let's move on to string concatenation. If I wanted to take two strings, then I can concatenate them with the dot operator. So if I have Milo as a first name and Banana as a last name, then concatenating with the dot operator and then putting a space in between will make a string that contains Milo Banana, which I can then echo or, rather, print out. Speaking of echo, let's talk about a few useful-- oops. I'm sorry. A few useful PHP functions. So we have the-- technical difficulties. One second. I sent it. PowerPoint problems. And we are back with PHP functions. And we are back with PHP functions. So we have the require function, where if you pass in a file, here's is just an example of a file that I might pass in. Then that will include the PHP code from that file that I indicate. And it will evaluate that in. Then we also have echo, which is a parallel to printf. Exit is a parallel to break, which exits the block of code that you're in. And then empty checks whether a given variable is like null or zero or whatever is equated with being empty. Yeah. AUDIENCE: For the string concatenation dot operator one, in PHP, is that the same as in JavaScript where it's using the dot for concatenation means plus? So for full name, you could have dollar sign first + and then + last? ZAMYLA CHAN: Yeah. So the question was whether in PHP we can use the same string concatenation as in JavaScript with the pluses. And Joseph will get into that later. I think he has a slide on that. Actually, it's different. So in JavaScript, you need to use the plus to concatenate strings. And in PHP, you have to use the dot operator. So they're different. OK. So now that we've covered all this PHP, where does it really come in handy? Well, it comes in handy when we can combine it with our HTML. So our PHP will give us the power to alter a page's HTML content prior to its loading. So based on different conditions, usually the specific user that's logged in, we can display different information. Linda, did you have a question? AUDIENCE: Can you concatenate an integer also? ZAMYLA CHAN: Yes, you can. So the question was if you can concatenate integers or other variable.s now, we move on to MVC, which is a paradigm that we used in pset7 and a lot of web designers use for organizing the code in the files in their website. M stands for Model. And basically, model files will deal with interactions with the database. View files, they relate to the aesthetics of the website. And the Controller handles user requests, parses data, does other logic. In pset7, we combined the model and the controller. And we just called them controllers and put them in the public directory. And the view files, we use them as templates in the templates directory. So this diagram here also represents that same kind of division with the model and the controller in purple here on the left and the view on the right. So this is a schematic that some of you may have seen at Office Hours or diagrams that we were drawing as you were figuring out your pset. So here, in a given controller, a model controller, we have functions that relate to querying the SQL database, executing PHP logic. Maybe you would look up a stock in Yahoo! Finance. Or perhaps, you would just check to see whether a user had submitted a form already before having visited your page. And then you would render a form over here. After that form had been submitted by the user, the action that was specified in the form's HTML tag would indicate the page that it returns that data to. So all of that information would be sent back to your controller. Then you would probably do a bit more logic on that and maybe execute a few more queries in the SQL database and then, finally, come up with a nicely packed set of information that you would pass in into some other template that displayed that information. Now, how do we actually package that information up? Well, we have a function called Render that was in the functions.php file in pset7, where you pass in the name of a file, the name of a template. And then you also pass in an associative array. And so that associative array represents the different information that you want to pass in. Now, what's going to be constant in these examples is that the keys or, rather, the keys of the associative arrays, those are what's going to be expected to be constant by the template, because it knows it needs something called message or called name. And then the things on the right, the actual values, so in this case, who's a good boy and Milo, those are going to be the values that are changing that the controller changes every time or based on a certain condition and will pass that in. So here in templates, we see that we are using HTML special characters, which just basically means that we want to get the peer string that the user put in. And we want to substitute message in there. So then when we actually view the file, the specific information is passed in. Note that the key how render works is that the keys of the associative arrays, those become variable names here. And so the values of that key in the associative array then becomes the value of the variable. Now, let's move on to SQL. It stands for Structured Query Language. And so this is just a programming language designed for managing databases. And it came in handy for us in our pset7 finance website. Essentially, it's just an easy way to track and manage objects and tables and link them to each other. Now, think of your SQL database basically as an Excel file, perhaps, with multiple tabbed sheets. So you could have multiple tables, perhaps, that linked to one another. And much like Excel, we have a lot of the functionality that we want. For instance, we can select certain rows. We can insert information. We can update rows. And we can also delete things. The SQL select works by selecting rows or a row of specified columns from a database that match a certain criteria that you indicate. So over here when I see select * from wizards where house = Ravenclaw, then I'm selecting *, which means I'm selecting every single column in that row from the wizards table but only if the house column equals Ravenclaw. Now, this is pure or SQL. So if I went into PHPmyadmin, which is the specific way that we use to manage our SQL databases, then I could insert that into the PHPmyadmin website. And that would execute. But we actually want to do that on the PHP side. So how do we do that? Well, we use the query function, which basically executes that SQL query. Using ? as a placeholder, we can pass in certain values to our string that we want to replace. So perhaps I'm storing different values in the curr_house, which represents the current house that I'm going through. So I can pass that in as a placeholder with the question mark. And then I'll basically execute the same thing as I did before, except now, I'm in PHP. And query will return an associative array. And I'm going to store it in rows. Now, query can always fail. Perhaps the SQL query couldn't execute because the table didn't exist. Or perhaps, the column didn't exist. Something went wrong. Well, in that case, you'll want to make sure that you check whether the query returned false. And that's by using the triple equals operation there. And then I apologize, which is another CS50 function, passing in a message. And if you look into apologize, all it really does is render apology.php. Yeah. AUDIENCE: Could you explain what that star does between select and from? ZAMYLA CHAN: Yeah, absolutely. So the star in between select and from means that I want to select the whole entire row from my table. I could've indicated select name, year, house. And I would only get those three columns in my table. But if I say select *, then I'll get everything in that column. Then I'm going to go you in the back first. AUDIENCE: So this is still in SQL, right? Is this query or is this PHP? ZAMYLA CHAN: We're in a query. So this is in PHP. So using the PHP function query, we're executing a SQL query. AUDIENCE: Is anything in SQL case-sensitive, like select or wizards or house? ZAMYLA CHAN: Is anything in SQL case-sensitive? I believe so, yes. I believe that SELECT and FROM and WHERE are case-sensitive. No? ROB BOWDEN: So, it's the opposite. The column names and the table means, all of those are case-sensitive. But any of the MySQL key words, like SELECT, FROM, and WHERE, those are not case-sensitive. OK. So the opposite of what I said. So all of the MySQL keywords-- select, from, where-- those are not case-sensitive. But everything else is. OK. You in the front. AUDIENCE: If I have $ rows in terms of more than one row, does that mean is just becomes an associative array? ZAMYLA CHAN: So the question was if rows has more than one row in it, does it become an associative array? So it is an array of associative arrays already. So even if there's only one row returned, then you'd have to go to index 0 of that result. And then you'd have that first row. Yes, Belinda? AUDIENCE: When you use ===, is this the only instance? Or are there others? ZAMYLA CHAN: So in this case, === is a comparison across types. Sorry. === is a comparison that compares the types. And then == compares across all types. AUDIENCE: Can you explain what rows is in this situation? Is it row of data? ZAMYLA CHAN: In the next slide, I'm going to explain what rows is. So if you don't mind holding off on that. And then you in the back? AUDIENCE: For functions like query, render and apologize [INAUDIBLE]? ZAMYLA CHAN: The question was whether these functions-- query, apologize, and render-- are common across PHP. These are ones that CS50 wrote for pset7. And Jay? AUDIENCE: When you need to say $_session, is that only for IDs? Or could you have said that here? ZAMYLA CHAN: So the question was, when we use $_session, that was a specific global variable that we're using. Here this variable is going to be local to our function. So we're just declaring a new variable. AUDIENCE: How is apologize implemented? ZAMYLA CHAN: The question was, how is apologize implemented? And I think this is actually a pretty good practice for you guys to go into the functions.php section and look at apologize and see how you could have done it yourself. So I may leave that to you but just say that if you look at apologize, then it takes the message that you submitted to apologize, and then it renders that message. Any more questions? I love questions. So keep them coming. AUDIENCE: [INAUDIBLE] echo or print there? ZAMYLA CHAN: The question was, could we not just have put echo or print there. So that would have done something slightly different. That would have printed query failed into that-- well, right now, we're actually in our controller. So we don't actually have HTML set up here. Apologize by rendering apologize.php actually redirects you to apology.php. OK. So now, let's go on to address the question from earlier about what really is rows. Well, query will return an array of rows. And every row is represented by an associative array. So if I've executed some SQL query and I've stored the result in rows, then using a foreach loop, then the array name is the first one there-- rows. And then I'm going to call every row in there $row. So iterating over that, I can then access the given row's name column, year column, and house column. Note that I wouldn't have been able to do this with rows, because rows index name doesn't exist. Rows is just an array of associative arrays. So you have two levels there. Once you have the array of rows, you have to get into that. And then you can access the columns. Did that make it clear? Yeah, in front? AUDIENCE: [INAUDIBLE] open brackets for [INAUDIBLE]? ZAMYLA CHAN: Pardon me? AUDIENCE: The open brackets. ZAMYLA CHAN: These here? That's allowing me to include that variable. Yeah. AUDIENCE: When you print, are you printing to the HTML code? ZAMYLA CHAN: Yes. When I print, this here is inside my template now, so my view of MVC method. So I'm printing into the HTML. AUDIENCE: So if we went into developer tools after running this, we could that actually in code? ZAMYLA CHAN: That's a great question, yeah. So if you went into the developer tools in Firefox using Firebug or Chrome, then yeah, you could see the specific HTML. So it wouldn't show $row["Name"]. It would show whichever name is in that row. AUDIENCE: Just a general issue, what are tr and td defined as? Why would we [INAUDIBLE]? ZAMYLA CHAN: Table row tr, table then td column. OK. AUDIENCE: Yeah, it's table data. ZAMYLA CHAN: Table data. Yeah. AUDIENCE: It's a row in which the row is treated like a column? ZAMYLA CHAN: Sorry. Can you repeat that? AUDIENCE: How would you visualize rows? ZAMYLA CHAN: How would you visualize rows in what kind of way? Are you talking about these rows here or the tr rows? AUDIENCE: The rows. ZAMYLA CHAN: These rows here? I'd visualize this as I execute my query. And it says, OK, I have either 0 to n amount of rows that match the criteria that you had queried. So I have some number of rows. So rows, the $rows, stores each one of those rows in an array. So even if it's just one of them, it's still an array of rows that match it. So then, for instance, this is similar to when you fetched the cache from users. And the criteria there was where ID equals the session ID. There really only is one row that could match that. But still rows just returned one row. So you'd have to go to rows, index 0, index cache to actually get to your cache. AUDIENCE: Is the print function in echo the same thing? ZAMYLA CHAN: Yes. Yes. Print an echo of the same. AUDIENCE: Is the foreach loop the only way to index into rows? ZAMYLA CHAN: Is a foreach loop the only way that you can iterate through rows? No. You can also use a for loop, provided that you know the length of the row's array. AUDIENCE: Could you access it using a row as [INAUDIBLE]? ZAMYLA CHAN: So you can't access it just using row if you don't have a foreach loop provided that you haven't declared row. Yes. Yeah, in the white. AUDIENCE: So what do tr and td do? ZAMYLA CHAN: So tr and td are HTML tags. tr indicates the beginning of a table row. And each td indicates a new table data column. AUDIENCE: For a visual of what a row is like, just imagine the SQL, how they have a row. [INAUDIBLE]. ZAMYLA CHAN: Yeah. That's a great point. You can visualize rows as just like in an Excel table, just the list of the rows. OK. All right. So now that we've gone over select, if there aren't any more questions, we'll go over onto insert. So if I wanted to insert into some table and insert certain column values, I could insert myself into Ravenclaw in year 7. But sometimes there might be duplicate values, as we saw in pset7 when we were updating our portfolio. So in this case, we want to use ON DUPLICATE KEY UPDATE, so that we don't store multiple rows with the same value but rather update it. Then we actually have update, which isn't an insert. It's just an update where you update in a certain table with a given criteria and then, finally, delete, which does a very similar thing. AUDIENCE: Could you briefly go over the duplicate key? ZAMYLA CHAN: Yeah. Essentially here, I have INSERT INTO gringotts, is, galleons, these values. But ID, presumably, is a unique key value set up in MySQL table. So if I already have that ID set up, then I can't insert a new row. So if it doesn't exist already, then I have to update it. In the middle in the white. AUDIENCE: So insert, update, delete, and select, are those all available locally [INAUDIBLE]? ZAMYLA CHAN: So insert, update, delete, and select are all SQL queries. So whenever you're using SQL, you'll have those available. AUDIENCE: Back to the past quizzes-- there was a question that dealt with if you had a table and wanted to insert test scores in one and you insert your name so it won't let you [INAUDIBLE] your friend's test score. How would you do that with insert? ZAMYLA CHAN: So the question was about a previous mid-term question. I'm not aware of which one it is right now. So maybe afterwards, if you want to come up and show me, then I can certainly give you tips. But speaking of inserting things, like taking someone's score when you shouldn't, let's talk about SQL injection attacks. So a SQL injection attack is essentially where someone takes advantage of the low security of the way that you are taking in data. So in here, just like in CS50 finance, when we logged in, we can enter in a username in the login form, the first text box, and then enter in a password. Perhaps our PHP code might look something like this, where $ username is the post-data username and password is post-data password. And then we just execute our query, say, OK, well, our query is going to select from our users, where the username is the one that they submitted. And the password is the password, meaning that the passwords match. Now, what if instead of actually submitting an actual password, like 12345 and guessing at prong that says password and trying to hack their account, what if instead they submitted this. They could type in maybe a guess at a password. And then they would finish the quote then type in or 1 = 1. That would pace directly into the SQL query to look something like this. Select from users where username = prongs and password equals lily or 1 = 1. So either the password has to be correct or 1 = 1, which is always true. So in this case, basically, a user can take advantage of this and just log themselves in and hack someone's account. So that's why we want to avoid someone having to do this. But luckily, the query function by passing in the placeholders will take care of this for you. Also, you'll typically never want to actually submit the passwords themselves. That's why we hashed or encrypted them in CS50 finance. AUDIENCE: The past quiz talked about MySQL escape strings. Do we have to worry about that? ZAMYLA CHAN: That's a good question. The MySQL escape strings is definitely a function that was used in our query. But definitely look into that. I'd say that's fair game to know that you'd need to call that function on a string. Yeah, Belinda? AUDIENCE: How do you know when it's single quotes or double quotes? And also, I feel like in lecture you mentioned something about not having the [INAUDIBLE] or something or the second single quote at the end. I think he pointed out in lecture that you're supposed to have apostrophe 1 and then not have apostrophes or something. AUDIENCE: [INAUDIBLE]. AUDIENCE: The thing is the last single quote in there in that second box shouldn't be there. [INAUDIBLE] Because when you take that last single quote out and match these for content where the password is, if you have that query, there's a single quote at the end already. You want to use that single quote as the one that faces the one [INAUDIBLE]. So what's actually in that text box should not have that. ZAMYLA CHAN: I'll change that. OK. If there aren't any questions, then I'll pass it over to Joseph to talk about JavaScript, et cetera. [APPLAUSE] JOSEPH ONG: So we are running a little bit behind. So if you have to leave, that's OK. But we ask that you keep your heads down if you're in the middle, so you don't block the camera and you use the back exit if you have to. I'm Joseph by the way. Hi. Test, test. Dan, is that good? Cool. So the video will also be posted online for those that have to leave now. Awkward. OK. So quiz review. This is a cat. Now, JavaScript, which is maybe not as aww for some of you guys. OK. So that's first, recall from Zamyla. Remember that PHP is run on the server. And lots of times, you guys wrote loops in PHP to print out HTML, right? So once that code executes, that HTML output that you print out gets sent to the user. And once that happens, no more PHP can be run, unless you reload the page, of course, which reexecutes the PHP. But once you print out that HTML, you can't go anywhere. So that HTML is sent over to the user, which is the browser over here, where Milo is using the computer. And so well, there are several things once we send HTML to the user. Sometimes we want to do something like when you click on something, we want alert boxes to pop up, those sorts of interactions, like when you press the key, when you click something on the page, I want something to happen. Well, you can't reexecute PHP code once that HTML is set. So how do you do this? We introduce a new language called JavaScript, which runs in the browser that allows you to do things to HTML after you receive them from the server. And this is why we call it a client-side programming language. It works on your computer-- the client. Any questions about that so far? That paradigm makes sense to people? OK. Good. All right. So the first thing to note is JavaScript is not PHP. They have some different syntax, which we'll go into. And they have very different uses. JavaScript, again, for your browser, for the client. Server runs somewhere on someone else's computer that sends information to you, correct? So if we ask you to write PHP code on an exam question, don't write JavaScript and vice versa. You'll just lose points, and it won't be right. So let's get into some syntax differences-- JavaScript on the left and PHP on the right. The first thing you'll notice with JavaScript, we declare variables with the var keyword-- V-A-R. PHP used the dollar sign, as Zamyla discussed earlier. If you want to declare an associative array, we see the familiar syntax on the right side with PHP. On the left side, instead you use curly braces. And then your keys are on the left. Then you have a colon. And then you have the values that you want. So this is how you would do it in PHP on the right side with that second line that starts at Milo. And that is how you would do it on the left side in JavaScript if you want what we call an object. And objects in JavaScript are just associative arrays. So if you want to access fields, in PHP you use this bracket syntax. And this way, you can reassign this owner field to Lauren. Well, in JavaScript, if one want to access a field and change it, you can use the dot syntax. You can also use the bracket syntax. But you can't use the dot syntax in PHP. That won't work. It only works in PHP. And finally, to print things to the console, you use console.log, which you guys use a lot in pset8. You can console.log that. If you want to print an array in PHP, you have to use print r. And on the right side, you see i hash string concatenation over there. Someone asked earlier. I use a plus in JavaScript. If I want to concatenate something in PHP, I use the dot. These are different. If you're writing PHP code, don't use a plus. If you're writing JavaScript code, don't write a dot. It will be wrong. And you'll be sad. So syntax differences. Know your syntax, because if you have to write a question and you use syntax from the wrong language, it will not work. And it will be wrong. So let's talk about some control flow differences, how you use loops in each of them. Zamyla went over the right side. Stuff on the right side should be familiar. Let's look at on the left side. When you use for n loop in JavaScript, your loop variable, var i over there, loop over the keys of the array. So you see name, house, and role. If I console.log i, I get name, house, and role. Those are the keys. In JavaScript, a foreach loop goes over the values of this array. So you notice they're both i. But in here on the PHP side, it prints out Milo, CS50, and Mascot. Those are the values in PHP. So these are how these two are different in the different languages. So if you're using a foreach loop, don't assume that it gives you the keys. And if you're using a for n loop, don't assume it gives you the values. Does this make sense so far? The next slide is going to show you how you can access the opposite in each of them. Well, if you have the key in JavaScript and you want the value out, you just index into the array with that. So Milo of i will get you what you want-- the values. There's this different syntax in PHP. If you really want to know it, I don't think we've showed it to you yet. But if you're interested, you can use this additional syntax on the right side that will actually let you get the keys in PHP when you're using a foreach loop. So just a little bit of trivia if you're interested. So that's just to demonstrate the differences between these two loops. Don't mix them up when you're programming a question. Any questions about that. Cool. All right. JavaScript objects. I talked about them. They're like associative arrays. The one thing I would like you to note here is that a value in an associative array can be anything in JavaScript. It can even be a function, like over there. I have a function that is a value of a key. And if I want to call that function, I just access bark. And then I put the parentheses after that. And that works. So any questions? No? OK. Good. JavaScript, like PHP, is loosely typed. What does that mean? It does have types. But when you declare a JavaScript variable, you say var i. You don't say it. That's not a thing. You just say it's a variable. And then JavaScript will handle the types under the hood for you. We can freely convert between types because of this. So i starts out as a number in this case. And then I have a string. And I add i to it. And I reassign it back into i. So on that first line, i is the number. On the second line, i now becomes a string after I do the reassignment. And here, I'm just concatenating that number onto the string. So you see that even though i was an integer in the first part, it's sort of like being converted to a string and then being added onto that hello string. And so that's what I mean by the loose typing. That's that you convert between types very easily. And it doesn't throw warnings at you like C does. So i now contains hello 123 to the string. Next. We can also freely compare between types. So if you just use ==, very much like in PHP, JavaScript does a similar thing. The string 123 is the same as the number 123 when you use double equals. When used triple equals, it also wants to make sure that the type is the same. So because that is a string and that is a number, even though they're both 123, when you use triple equals, you get false. In the double equals case, you get true, because double equals doesn't care about type. Triple equals does care about type. Questions? OK. And another thing about JavaScript is scope is kind of global unless you're in a function. And it works the same way in PHP actually. So let's go through this example. I set i to 999. And then I go into this for loop. So if I'm printing i out in this for loop, I expect 0, 1, 2, 3, 4. I get to i = 4. It increments i now to 5 at the end of the for loop. And then it breaks out of the loop, because it doesn't fulfill the condition anymore. What do you think that next console.log prints out? So that's what it would do in C. In C, because if you have like var i outside and you have var i inside a loop, like a for loop, then it makes it such that it's scoped that the two i's are different. In JavaScript, it will just treat it as the same i. I get 5, because that was the value after it exited out of the loop. So those i's are the same i. Does that make sense? Well, it makes sense from a JavaScript standpoint. But the same paradigm doesn't carry over to C. They have different scoping rules. Yes. AUDIENCE: [INAUDIBLE] outside the function [INAUDIBLE]? JOSEPH ONG: So outside which function? So I'll get to that in just a second. So we call foo(i). This passes i into foo, increments it, and then logs it. So it was 5. So it becomes 6. But what I'm talking about is that i in that function. Because it's a parameter, it's scoped to that function. So once I actually get out of that function, it's now going to go back to the old i. That i is only scoped because it's in a function. And we have scope and functions. But we don't have scope outside of functions in JavaScript. Does that make sense? Yes. Question. AUDIENCE: Same [INAUDIBLE]? JOSEPH ONG: So yeah. In PHP, it's the same type of thing. There's a slight subtlety actually. But you can ask me about that after the review. You don't really need to know that subtlety for the quiz. For all intents and purposes, like variables, global and PHP, unless they're in a function, same thing in JavaScript. Yes. AUDIENCE: Why is this allowed in JavaScript and no where else? JOSEPH ONG: So why is it allowed in JavaScript and not in C? It's just whoever came up with JavaScript decided that this was OK in JavaScript. So it's just like a programming language convention as we would say. Yes. AUDIENCE: So why did it go from 6 to 5? JOSEPH ONG: So it went from 6 to 5, because when I passed i into foo, that i inside of foo is now scoped to foo, because scope exists in functions in JavaScript. But once I get out of here, because it was scoped to the function, I'm just using the regular i that was inside the rest of the control flow. Make sense? Can I move on? All right. Cool. The acceptance of this is objects are passed by reference. You know how when you pass an array into C you could actually modify the array? It's the same thing in JavaScript. If I pass an object, in this case, I passed Milo into this catify function. Milo starts out. His name is Milo Banana. I pass that object into a function because it's an object, an associative array in JavaScript. When I perform an operation in that function, it will actually change the object. So this will only happen for objects in JavaScript, just like it happens for arrays inside of C. So Milo's name will actually become cat now. Does that make sense? So this only works for objects. Objects are passed by reference. Yes. AUDIENCE: So you're saying that in contrast to variable i. JOSEPH ONG: Yeah. Which variable i was just a number, right? It's like in C when you pass an integer a, it makes a copy. And when you pass an array, it actually changes the actual array in C. The same thing happens with JavaScript in this case. All right. And next, Milo is sad because he's now a cat. That was actually Milo after some trip to the vet. So how do we use JavaScript in a web page? We can include it. This is HTML code with the strip tags. So I have strip tags there. And then I put some JavaScript code within the script tags. And then it executes this. When I just do it like this, it's called inline JavaScript. It's kind of messy, because the JavaScript is actually in the HTML. A better way to do this, much nicer, is to write your JavaScript in an external file and then provide the script tag with a source. And this will go to that JavaScript file and read the JavaScript code from that file instead. And this way, you don't have a lot of JavaScript at the beginning of your HTML file, which makes it really messy. You just put it somewhere else. And then it will read it from there. Did that makes sense? Placement matters. In this particular case, the script is before the body. So when I execute that, there's nothing in the body yet. Maybe this will make a little bit more sense when I show this next part. In this case, the script comes after the div. So the div actually appears on the page first. Right here in this little red circle, you see the text appears. And then the alert shows up. In the first case, because the script was before the div, the alert shows up first. And then the div shows up after you dismiss the box. So the execution matters. So we'll keep this in mind. This will be important in a little bit. OK. So well, how do you wait until the entire page is loaded then before you execute some code? We'll get into this a little bit later too. But just keep this placement matters in mind for when we come to another slide. So we get to DOM now. And what is DOM? So if you look at HTML code, it's just a bunch of text on the screen. So how does JavaScript know that this is an HTML element? So we have to have some memory representation of this structure that we have. And whenever we have this in memory representation in JavaScript, we call that the DOM. And it's just a way that people decided that we should represent this HTML structure as. And what does this DOM look like? Well, in memory representation, we take this text. And we turn it into memory representation. So this is the HTML. So we first find out that every DOM tree has a document. It looks like a tree. And the document contains the HTML tag, actually everything inside of this now. The HTML tag has two children. It has a head. That head, if you look at indentation over there at how it's structured between the close tags, head has a child. The child is title. Exactly. Now, we have a body child. And then that body has a child called family. And that family has three children-- oldest, middle, and youngest. So you should know how to draw a diagram like this when we ask you how to draw a diagram when we give you the HTML on the left. Know how to produce the DOM tree. And inside of these things, there's just some text, which I've represented as little boxes. Does this DOM tree structure make sense and what the DOM is? So what does the p stand for? Over here, the p over there in that tag represents a paragraph tag in HTML. So you can look it up. But it just means it's some space for some text. And it has some default CSS styling, because it's a paragraph tag. But don't really worry about that part too much. Just know it's a placeholder for some text. Yes. Question? Yes. AUDIENCE: You just mentioned CSS. The hash family and the hash all that stuff is basically representing IDs in CSS? JOSEPH ONG: Yeah, exactly. I'll get to what these hashes mean in a second. When Angela went over CSS, she talked about CSS selectors. These are the CSS selectors that she was talking about. Yes, Rob? ROB BOWDEN: I would also comment that DOM inside of title tag is also a text node. JOSEPH ONG: Right. So inside the title tag, I have some text DOM. So really, this title should have like a little box coming off of it as well. But it doesn't really matter too much in this case. We don't really care about text nodes, as we call them, too much. OK, we do. Apparently, we do. And I will fix that when I upload it again. Does that make sense? So how do we work with the DOM? Whenever you deal with the DOM in JavaScript, there are two steps. You select a DOM element. And then you do things to it. So in this case, abstractly, I've selected the middle element. And then an example of doing stuff to it would be changing the text. That used to be Bob. Now, what I did to it was I changed Bob to Milo in this case. So how do we actually do this? How do we do the selecting? And how do we do the doing stuff to the thing once we've taken it? Well, the way you guys have learned it in this class is by using something we called jQuery. So what is jQuery? jQuery is a library that makes JavaScript easier to write. So someone took the time and wrote jQuery. jQuery is actually written in JavaScript. And then because they did this, we now have a whole bunch of functions that we can use that make our lives really easy. So what are some of the things it does? It makes selecting elements easier. It makes changing HTML, adding classes easier. It makes Ajax easier. We'll get to that in a second. And it's analogous to C libraries. So you include string.h, you get strlen. You get strcpy, all of these things. When you include jQuery, you get nice ways to select elements to change things, et cetera. You get extra functionality that JavaScript doesn't give you. So jQuery is not JavaScript. jQuery is a library that's written in JavaScript that makes JavaScript easier to write. So jQuery is not a programming language. But JavaScript is. make. Sure you get your terminology right. Any questions? Yes. Is that a question? All right. So how do you use jQuery? Well, when you're writing some JavaScript code and you include a jQuery at the top of your file as a script file, you use the dollar sign now to get access to jQuery. And this is different from the dollar sign in PHP. It's the same symbol you type on your keyboard. But they mean very different things. Dollar sign in PHP means this is how I declare a variable. In JavaScript, when you've included jQuery, it stands for jQuery. So keep that in mind. So how might we select DOM elements? Well, when you do it the ugly JavaScript way, you access the document global variable. And then you get element by ID family. This is really long and wordy and not very nice. Or you can get all elements that are a p tag. That works too in JavaScript. But we never really showed you the syntax too much. What we showed you was jQuery. So that entire selector up there that was expressed in JavaScript just gets condensed to this very nice dollar sign hashtag family. And $ p, just where it's like that. If you want to select all p tags inside a family, we put a space between the two. And now, we get all the p tags inside a family. And look familiar? Well, Angela talked about CSS selectors. Give me one second. And so in order to select an element, you just use the same thing as you would do with a CSS selector. If you put a hash in front of it, it selects by ID. A dot selects by classes. If you just have the thing without hashes or dots, it selects those tags. Questions. Yes? AUDIENCE: When we use dot in our HTML, is that not jQuery? JOSEPH ONG: Dot in our HTML is a JavaScript thing. It's not a jQuery thing. The way you guys learned it with jQuery is to use .html. And then you passed it whatever the HTML is going to be. So I'll get to that in just a second actually. So how do we do stuff to element once we've selected it? So that's an example of selecting an element. So now, we want to do stuff to it. So in this case, let me go back to the previous slide. It was Bob before. And I want to change that inside HTML to Milo. So I call the HTML function from the element. That HTML function is a method of element. And then I give it what I want the HTML to be. And it just replaces what's inside of that tag with whatever I give it. Yes. Question? AUDIENCE: The hashtag is used for only the jQuery. [INAUDIBLE] we wouldn't use that. JOSEPH ONG: Yeah, exactly. But don't worry too much about pure JavaScript. I just want you guys to focus on how you would do it with jQuery, because that's going to be the important part on the quiz. Right. Exactly. So you see that hashtag, so that corresponds to select the element with the ID middle because of that hashtag. Hashtag means ID. And this element has an ID of middle. So that's the element we select. AUDIENCE: [INAUDIBLE]. dollar sign hashtag [INAUDIBLE]? JOSEPH ONG: So no. The question is can you use .value. And .value only works on elements that are inputs. In jQuery, it would be .val, not .value. So I'll get to a small example that demonstrates all this in combination in a second. But I think this serves a little snippet makes sense to people so far. Want to change the HTML, call the HTML method. Yes. AUDIENCE: Can you explain the method again? JOSEPH ONG: So a method is just a function that belongs to one, in this case, one of these DOM elements, because you see I selected the element first. Actually, let me use the mouse. I selected the element first. And then I called this HTML function that it had. And because this function belongs to this thing, we call it a method. That's just a fancy name for it. Say that again. So remember, we selected the element now. And we've put it inside of the element variable. Correct? So when we want to change the HTML on inside, because it was Bob before, you want to change that text to Milo. So we call HTML. And we tell it what the HTML inside that element should be now. And so it changes it to Milo, because I gave it Milo. AUDIENCE: So they're working together. [INAUDIBLE] JOSEPH ONG: Yeah, yeah. They're working together. So one of them selects the element first. And the second one does something to it. Yes. AUDIENCE: [INAUDIBLE]. If this method is different from in HTML you have the method equal actual. JOSEPH ONG: Yeah. That is a different method. That is a different method. And we can cover that in just a second when we get to an example. I want to make sure that we speed up because we're running out of time. But we've run way over time now. OK. Cool. So if you want to add a class, there's also an add class method. This is just an example of what you can do with jQuery. That just adds a class. If you want to remove it, you can call remove. That's just another thing you can do. So more examples of things you can do. So can I just put it at the top like this? Youngest remove. If I just execute that JavaScript at the top of my file, will that work? Right. Because middle doesn't exist yet. So this is not going to work. Execution order. It goes to the top first. What? AUDIENCE: Youngest doesn't exist yet? JOSEPH ONG: Yeah. Youngest doesn't exist yet. Exactly. AUDIENCE: You said middle. JOSEPH ONG: Sorry. Youngest doesn't exist yet. And the other thing is I haven't included the jQuery file ask script src. So that's not going to work. Actually, I didn't do that in the next slide, which is supposed to fix that either. But the way we do this is JavaScript is event driven. So what we do is we use an event handler to make this happen. And so I select the document set first. I say, OK, when the document is ready, let me run a function. So that's all that syntax means. I selected the document. Now, when the document is ready, run the function. And so over here when the document is ready, which means all the HTML has loaded, then I run the function that removes that element. And so now, when I run this function that I passed into ready, I'm guaranteed that all the HTML on the page is going to exist first. Yes. Question? AUDIENCE: What is the event keyword within the function? JOSEPH ONG: So that event keyword in the function is just a parameter that gets passed to the function for any event. It's just something that you get for free. When you are using key handlers in pset8, that event could tell you, for example, which key you pressed on. In this case, for a ready event, it's actually not super useful. But for a key down event, it's more useful, because you get to know which key you pressed by accessing key code off that event object. Correct? Does that make sense? OK. Yes. Question? AUDIENCE: So can you put the script tag lower down? JOSEPH ONG: So yeah. You could put the script tag lower down. But then it just becomes really messy. And we like to centralize all of our code in one place. And this will allow us to do it. Remember earlier I said there's a nicer way to ensure that elements are on the page before you execute code? And this is just a nice way you would accomplish that. AUDIENCE: [INAUDIBLE]. JOSEPH ONG: Yeah. You would still have to, right? Because remember, you included the file at the top of the page. So it's going to execute first before you get to the bottom of the page. OK. So you can also add a different type of event handler. This one just processes clicks. When I click on youngest, then it will pop up with an alert. This is just a different type of event. As opposed to the ready event, you now use the click event when you receive clicks on an element. And so in this case, remember, the click handler is attached to youngest. So it only happens when I click on youngest. And in the other one, the ready event was attached to the document. So it waits for the document to be ready. Make sense? I think I can move on. Yes. Question? AUDIENCE: [INAUDIBLE]. in this case you use [INAUDIBLE]. JOSEPH ONG: Oh, yeah, because in this case, I have to wait for the youngest element to appear on the screen first before I can attach a click handler to it, which is why I put it inside of a document ready. OK. And next, so this is a big example of how you would combine everything. This is just a form validation example you've seen in lecture. So take it step by step as you go through this. And it will be totally OK. Just read it from top to bottom. I have a form at the bottom. When the document is ready, I attach a submit handler to the form, such that when I submit the form, I get the values inside each of those inputs. And I check if it's blank. If it's blank, I return false, because I don't want to submit the form, because the form is wrong. If the password is blank or it's less than eight characters, I don't submit the form, because that's also wrong. And the return false just prevents the form from submitting and going to a new page. And hopefully, this makes sense. I think you guys should walk through this code step by step on your own. And once you understand what the select elements and do stuff to it actually entails, this will make a lot of sense to you. Yes? AUDIENCE: What does the name = username mean? JOSEPH ONG: So the name = username and name = password just means look at the attribute of whatever you're selecting. And then that has to match. So we go into registration. And then we look at all inputs and registration. And then we pick the one where the name attribute is equal to username. So that first selector only selects the username input. And that second selector only selects the password one, because those have their name attributes set as what they're supposed to be. Question? AUDIENCE: On submission, how does the bottom part resolve the top part? JOSEPH ONG: So that's because of the event handler. So we're waiting for a submit event that gets fired from the form. And that's all that is submit. Why do I call submit up there? It says, when the form is submitted, I get a submit event. So let me just intercept that and then run this code instead. Yes? AUDIENCE: Why do you have to have function event? Why can't you just [INAUDIBLE]? JOSEPH ONG: Because in JavaScript, you have to declare the functions. That's just how it works in JavaScript. You have to say it's going to run a function. So you're telling it that you're expecting a function here instead of just curly braces. AUDIENCE: And the function is whatever follows? JOSEPH ONG: Yeah. The function is whatever is inside the curly braces after that function keyword. Yes? AUDIENCE: [INAUDIBLE]. JOSEPH ONG: For submit? AUDIENCE: No, for function without the event. JOSEPH ONG: Yeah. So without the event, you can have that. If you don't need the event, then you can just omit it. But if you do, then you just put it there. Yes. Quick question? AUDIENCE: [INAUDIBLE]. JOSEPH ONG: Yeah. Because what you need to do, the document.ready just says wait for all the HTML on the page to load first. And usually, you want your elements in place before you run any code. All right. We have to get to Ajax. We don't have much time. So pros and cons. JavaScript is easier try write with jQuery. But jQuery is kind of slow. It's like PHP is slower than C, because it's interpreted. And jQuery is a bit slower than JavaScript, because it does a lot of things under the hood. And so if you're using jQuery, it's just a little bit slower than JavaScript, even though it gives you nice elegance. And finally, Ajax. So far with Ajax, you haven't seen Ajax in terms of pset7 yet, because when you do, you submit a form to quote. It loads a new page. So you get this big white flash on the page while that second page loads, correct? It would be really nice if you didn't have this flash. Like Facebook, if you just scroll to the bottom, it adds new content without refreshing the entire page. So something like this would be nice. This is JavaScript code on the left side. You get what is inside of that input. You get the stock info from Yahoo! And then you make a big string that says, OK, this is the message I want to show on the screen. And then you put that message inside of some HTML element that gets displayed on the screen. So that's all that's happening here. So basically, because this is all JavaScript and you don't need to run anymore PHP, this will make sure that the page doesn't refresh. So this is just an abstract idea that I'm saying here for now. The abstract idea is that if you do it all in JavaScript, you don't have a page refresh. But how do you actually do this? Well, actually, let's talk about a problem with this first. A problem is in JavaScript, execution is synchronous. So you have to wait for one line to finish before you execute the next line. And what if I'm going over to Yahoo!, and their servers are really slow, and it takes them three seconds to give me back that stock info? When I hit that price line, if the execution is synchronous, as it is by default, what it's just going to do is your browser is going to stall for three seconds. And you're not going to be able to do anything while it gets that data. It's going to be frozen. And that's bad. You don't want a user to have a frozen web page. Correct? That's just bad. Everyone agrees? If you're browsing Facebook and it freezes and you can't do anything, you get really frustrated. So the solution is we make something asynchronous instead. So all this asynchronous thing says is, I'm going to ask this URL for some data. And then I'm going to keep going. I'm just going to keep executing whatever code that was after that. And then whenever that data is ready, then I will process it. That's all it is saying. AUDIENCE: Ajax just makes code asynchronous? JOSEPH ONG: It's an asynchronous way of fetching data. So the first thing about Ajax is it lets me get data from an external website. And the second thing is it makes sure that my page doesn't stall while I'm fetching that data. That's the asynchronous part of it. Because it goes off somewhere else, because I say I keep going on while it's fetching that data, that makes it asynchronous. I keep executing. So keep that asynchronous idea in mind. And I'll show you what the difference is. The synchronous version is on the left side. The asynchronous version is on the right side. Look at the numbers to see which steps correspond to what executes at each line. Over there, the alert shows up first. Because getting stock info from Yahoo! takes three seconds, it stalls for three seconds. And then it alerts the price after those three seconds. So now, that alert shows up at that time-- three seconds in. And then it alerts by after that. So it just goes step by step. It's like what you guys would accept, correct? With asynchronous execution, you alert first. Then you go off to this URL. And you say, I'm going to just ask for the data. And then I'm going to process it later. So it immediately executes the next line after I make that asynchronous request. So a 0.001 seconds, you see alert hi. Execute that function, alert bye. And because I made a promise that I would process the data later, what happens is when that data comes back three seconds later, then I run that function that I have over there. Yes? AUDIENCE: Could you specify or clarify what Ajax means? JOSEPH ONG: So Ajax is a way that if I need data when I'm on a website and I don't want to refresh the page, then I use this technology called Ajax. That essentially just means, go fetch data from another website. And do it in a way that just doesn't stall my web page. AUDIENCE: So is that an inherent part of JavaScript or jQuery? JOSEPH ONG: So someone wrote a way to do this in JavaScript a long time ago. At one point, it didn't exist. And so someone invented this technique to allow people to request this data in this fashion. And they wrote some stuff to do it for you. And jQuery just gives you this very nice way to do it with this $.get function. questions? I can answer questions about Ajax afterward too. I'll be here. So it let's us fetch data without refreshing the page. And it let's us do this in an asynchronous way that doesn't freeze the page. Too long, didn't read if that explanation was too long for you. So finally, cross-site scripting attacks. We saw this with Zamyla. If in my database someone has this name, which is this script tag, and I have some code on my page that prints out people's names in a row, or I have some JavaScript code that inserts this name into the page, what HTML gets produced? Well, I print out the HTML tag. I print out all these tags. I get to the part where I'm printing out with my friends. I print Lauren out. It print Milo out. And then my name in the database is script post unflattering Facebook status. Because I inserted this into the page because it looks like JavaScript, when this page gets sent to the user, it gets executed as JavaScript. And so this is what we call a cross-site scripting attack. Someone puts malicious information in your database that could correspond to some additional string or some JavaScript string. And when it gets printed out to the page in this fashion, then what happens is that bad code gets executed that I didn't intend for it to get executed. And that's all a cross-site scripting attack is. And the way you get around this is like Zamyla said. You just wrap things in HTML special chars. And this HTML special chars is a PHP function that will prevent this sort of thing from happening to you if you have a malicious string in your database. It just escapes it, so that it doesn't get interpreted as HTML. It replaces the little brackets with what we call entities. And we went over this in lecture too. So I think you guys should have a good grasp on that. Questions? Yes. AUDIENCE: So how would the [INAUDIBLE]? JOSEPH ONG: Say that again. AUDIENCE: How would the monitor-- JOSEPH ONG: Right. So you have something that says, when I register, type in my name. I just type in that field, my name is stript post unflattering Facebook status close script tag. And that just gets put into the database, because I can't say someone in the world doesn't have a name with a left arrow in it or the word script in it. That doesn't really make sense. So I just have to make sure that I sanitize the stuff before I print it out to the page. AUDIENCE: So the HTML special cards prevents the script tags? JOSEPH ONG: Yeah. So it doesn't prevent the script tags. It just makes sure that the script tags don't get interpreted as HTML or-- yeah. It just comes up as what it actually is. All right. So that was the quiz review. Cool. [APPLAUSE]