Introduction to OO and the DOM
Modern programming techniques utilize what is called Object Oriented Programming. Objects are basically self contained things that contain other things. They're Objects.
Before you create an object, you have to write a class. A class is simply the piece of code that defines what an object is and what kind of stuff you can do with it. Writing classes are a bit beyond the scope of this section. We'll just go over what an object is and how to use them.
Lets use an analogy. What's an object that everyone can relate to? How about balls? Okay, so a "ball" is an object in real life, and we'll use a "ball" as our object in programming.
Objects are made up of two types of parts: Methods and Properties. Typically, you can access an object's parts using "dot notation". Object.Method() or Object.Property ... not too hard.
A method is just a function that is owned by an object. It can either be something that the object does, or it can be something that can be done to the object.
For our example: You can kick a ball. So if kick() is a method of our ball object, and you wanted to kick the ball, you'd do ball.kick(). Balls can also explode. So, if you wanted to make the ball explode, do ball.explode().
A property is something that describes the object. Or another object that the main object owns. It's important to note that properties are not functions, so you don't put () at the end.
Back to our example: Balls might have a size. So, maybe ball.size might return "big" or "small". Also, balls might have hair. ball.hair would return a hair object.
Hair is another object, so it'd be like a 'sub-object'. Hair would probably have some methods and properties of its own. You might want to pluck one of the hairs off the ball: ball.hair.pluck(); or maybe you want to find out what color the ball's hair is: ball.hair.color might return "blonde" or "black".
So, there's your crash course in object oriented programming. We'll probably go into more details later.
Now, because we're still in the "Output" chapter, you might be wondering what these objects have to do with outputting anything. That's where we get to the DOM or Document Object Model.
Web pages are like one giant object with sub-objects and methods that can be used to manipulate the page and the objects within the page.
The top level, root object is the window. The alert() function we used earlier, is actually a method of the window object. You could, if you wanted to do window.alert("vrimples"); and get the same effect. Window is an exception, however, in that you don't have to write it everytime. It's kind of assumed.
Probably the most important property of the window is the document. Document is everything that is displayed in the window. This is where most of the good stuff goes down.
Document has a method called write(). It writes stuff to the document. Example:
<html>
<head>
<title>My First Webpage</title>
<script type="text/javascript">
document.write("VRIMPLES");
</script>
</head>
<body>
Balls!
</body>
</html>
Instead of using alert() to output "VRIMPLES", we use document.write() ... Which simply writes out "VRIMPLES" when that line is parsed.
Now, that's a good way to output stuff into a web page using javaScript, but there's another way that I prefer. It's a little more involved, but you can do a lot more with it. The following code is a modified version of our original code, but knowing what you know about objects, I think you can handle it.
<html>
<head>
<title>My First Webpage</title>
</head>
<body>
Balls!
<div id="output"></div>
<script type="text/javascript">
document.getElementById("output").innerHTML = "VRIMPLES";
</script>
</body>
</html>
Here, we're introducing a few new elements. An important thing to remember is that each element is essentially a property or sub-object of document.
The first new thing is the <div> tag. <div> creates a new block element. It stands for "division". Div's are mainly used to create sections of HTML and divide it from other parts. Block elements are separated from the rest of the rendered html, placing a new line above and below that section.
This particular div has two properties that we play with. The first is the "id" property. Here, we're defining it inside the tag itself and, thus, is set as soon as the div is rendered. id makes it much easier to access via javascript.
The <div> is followed by the javascript. Note that we've moved the javascript down, below the <div>. This is because the <div> must be created before we can access it with the javascript. The browser parses the code from top to bottom. If we kept the javascript in the header, the browser would try to access the output <div> before it is created and would return an error. Having the javascript at the end allows it to access the div, now that it's created.
Now, the new line of javascript: document.getElementById("output").innerHTML = "VRIMPLES";
What this says is "use the getElementById method to grab the output div, then set the output div's innerHTML property to "VRIMPLES".
getElementById() is a method of document. For the most part, the pre-defined methods do exactly what the name implies. getElementById() gives you access to the element with the id specified in the parameter list. That's why we needed to specify the id in the tag itself--so that we know what element we're trying to access.
In my opinion, this is the easiest way to access elements. There are other ways to do this, utilizing different functions which "walk the object tree". I like this way, though. It's nice and simple.
So, getElementById() gives you access to the element. Basically, the code is substituting "document.getElementById("output")" with "the output div". The javascript now thinks that it's doing 'outputdiv.innerHTML = "VRIMPLES";' Of course, you can't access the 'outputdiv' directly, so this is the next best way.
The output div element has its own set of methods and properties. One of its properties is innerHTML. As you've probably guessed, it contains all the HTML that is inside the element. With this property, you can 'get' and 'set' the inner HTML.
You can set the value of a property by using the '=' operator. It's important to realize that this is really an "equals" operator, it's a "set" operator. Instead of "innerHTML equals VRIMPLES", it's more accurate to say "innerHTML is VRIPMLES" or "innerHTML becomes VRIMPLES".
What we're doing is putting the value of "VRIMPLES" into the innerHTML property of the output div. We'll be using the = operator a lot from now on.
To summarize: Create an empty <div> element with an id of "output". Using the getElementById() method, grab the div with an id of "output" and cram "VRIMPLES" into its innerHTML.
Not so hard, right?
Next time: Variables.
Wisdom Archive
- August 2008 (2)
- July 2008 (2)
- June 2008 (3)
- May 2008 (3)
- April 2008 (4)
- March 2008 (7)
- February 2008 (6)
- January 2008 (1)
- December 2007 (3)
- November 2007 (9)
- October 2007 (26)
- August 2007 (1)
- June 2007 (1)
- May 2007 (1)
- March 2007 (1)
- February 2007 (2)
- December 2006 (4)
- November 2006 (4)
- October 2006 (5)
- September 2006 (2)
- August 2006 (1)
Categories
- poonheads (22)
- music (17)
- comic (16)
- site news (12)
- coding (11)
- Classic Wisdom (10)
- video (10)
- I Love Music (9)
- javascript (9)
- photo (9)
- rant (8)
- tutorial (8)
- web design (8)
- hardware (7)
- hobby (7)
- mustaches (7)
- gear (6)
- horrifying (6)
- story time (6)
- earworm (5)
- food (5)
- art (4)
- software (4)
- Coding for Complete Noobs (3)
- movie (3)
- Captain Numbskull (2)
- Everyday Wisdom (2)
- beverage (2)
- knives (2)
- review (2)
- toys (1)
Wednesday, March 26, 2008
Coding for Complete Noobs: Chapter 2 part 2
Tuesday, February 26, 2008
Coding for Complete Noobs: Chapter 2 part 1
Chapter 2: Output
Part 1
Output is the data that is put out from the program. Go figure. The program runs and spits out the results. That's your output. It's pretty much the only way to tell if your program is doing anything. Sure, you could make a program that that counts to one thousand, but what's the point if you can't watch it count?
It's true that the plain html that we made last time is a form of output. The only problem is that it's static. You save the file and open it in the browser and it doesn't do anything except print out the contents of the file. Nothing happens.
To make the page "do stuff" we need to add in some javascript. Javascript enhances webpages with interactivity. When the user does something to the page, the javascript will do something in response. In order to let the user know that something just happened, you'll need to be able to output a message.
On with the code... We'll start with the page we created last time, but with modifications to add the javascript:
<html>
<head>
<title>My First Webpage</title>
<script type="text/javascript">
alert("Vrimples");
</script>
</head>
<body>
Balls!
</body>
</html>
You'll notice the <script> tags in the header. That's where your javascript goes. The <script> element can actually go anywhere in a page, but it's generally preferred that you keep most of the code in the header. As with all rules, however, there is a time and a place for breaking it. Sometimes it's necessary to throw a bit of javascript right in the middle of a paragraph. Just try to keep it to a minimum.
The <b>type="text/javascript"</b> part of the script tag is called an 'attribute'. It's just an extra bit of info about the element that, in this case, tells the browser that the following code is of type "text/javascript". Depending on various factors, the script may or may not work without the type attribute, so you must remember to add it in there.
Inside the script element is where the real fun begins. Instead of just marking up text, as with HTML, we'll be writing actual real code that will do stuff. This simple example simply pops up an alert box with the word "Vrimples". That's what the alert() function does. There are several other ways to output messages to the user, but we'll start with alert() because it's simple, easy to use, and will allow me to introduce a few important programming concepts.
alert() is an example of a function or method. Functions and methods are pretty much the same thing. Later on, when we get to more advanced topics, I'll explain the difference, but for the time being, just think of it as two words for the same thing.
Functions are like actions. When you call a function, the script preforms that action. I like to think of functions as the 'verbs' of programming.
Each function has several parts. In our example, "alert" would be the function name. That's simple enough, right? The name is always followed by a pair of parentheses (). That's how the program knows that it's a function. If you don't put the parentheses, the browser will not treat it as a function and may return an error.
Inside the parentheses is the parameter list. Parameters are bits of information that you pass to the function. The function will take this information and manipulate it or use it for calculations or for whatever it is that the function does.
In this case, alert() only takes one parameter. "Vrimples". "Vrimples" is a <b>string</b>. A string is a group of individual characters that are lumped together with quotation marks. In javascript, you can use either single quotes (') or double quotes ("). You just have to make sure that you use the same type of quote at the beginning and end of the string. The first quote tells the browser to start making a string and the ending one tells the browser to end the string. Other programming languages require you to only use single quotes or to only use double quotes. But since we're not worried about other languages at this point, we'll just forget about it. Just remember to remain consistent.
Something to think about: Supposed you wanted to print out a string with a quotation mark in it... for example: She said "Vrimples". You might try putting alert("She said "Vrimples""). This won't work. Why? Because the browser treats the second quotation mark as the ending mark and starts a new string at the third quotation mark. So what do you do?
You have to use the escape character. In javascript, the escape character is a backslash (\). It tells the browser "The next character after this escape character should be treated differently than it normally would be." So, you would end up with <b>alert("She said \"Vrimples\"")</b>. That way, the browser interprets only the first and last quotation marks as starting and ending the string. It simply prints out the quotes around Vrimples.
But back to our sample code... So you have the alert() function that takes one single string parameter (which, in our example, is the string "Vrimples"). The browser reads that and pops up an alert box with the text "Vrimples" in it.
This is all followed by a semicolon (;). The semicolon tells the browser that it's at the end of a command. It's kind of like a period (.) when you're writing in English. In javascript, the semicolon are optional. You could just have every line of code on a separate line and the browser would treat the line-breaks as semicolon. However, almost every other programming language I know requires you to put a semi colon at the end. Since it won't hurt anything, end every line with a semi colon. It will eventually become a habit that will transfer to other languages, should you decide to learn one.
That right there is the basic syntax of javascript. Just about everything builds on that. Of course, you'll need to do some stuff other than just popping up alert boxes. I would imagine that most tutorials and manuals and books would start talking about variables, loops, functions, and a whole lot of other important fundamentals. We'll get to that later.
My philosophy is 'learn how to do the hard stuff, then go back and learn the basics so you can make the hard stuff more awesome'. That's why in the next chapter, we're going to talk about Object Oriented Programming and The Document Object Model.
Having come this far, hopefully you're enjoying yourself and learning something. If I'm going to fast or throwing too much at you at once, I can pretty much guarantee it's only going to get worse. This here is where things start getting crazy, so hold on to your hat as we jump right in to the thick of it.
~Ben
Thursday, February 14, 2008
Coding for Complete Noobs: Chapter 1
Kids today take computers for granted. They play on the YouTube and their MySpaces and really have no idea what it takes to create such fantastic pieces of software. I do. Because I'm a programmer.
When I explain to people what it is that I do for a living, I get one of two responses. "Oh, that's nice." or "I could never do that." Sometimes both. The later of the two is not entirely true. You just need instruction from someone who can speak your language.
That's what I'm attempting to do here.
--
Before we get started, there are a few things that you should know. This first part is very long and might be kind of boring, but it's vital if you hope to understand anything further down the road.
Programming, or "coding", as we call it, is the process of writing words and numbers and symbols (or "code"). That code is run through a compiler or an interpreter which transforms the code into a program. It's just that simple.
All websites are created in such a fashion. A programmer will write code (sometimes utilizing other programs to assist in the code writing) and your web browser acts as an interpreter which translates the code into a web page. You can readily view the source code of any given page by right-clicking the page and selecting "View Source".
Technically, however, websites are not generally considered programs. Programs are created by running the source code through a compiler which produces a separate application that can be run completely independent of the compiler. Websites are interpreted, which means that the code has to be re-interpreted every time you view the page, and thus are completely dependent on the interpreter. "Programs" written in interpreted languages are typically called "scripts". I think (now, don't quote me on this) that they are called scripts, because it's like an actor reading a script and acting it out. Whatever the case, I almost always refer to web pages as simply "Web pages" or "Web sites".
So... Web pages are actually just source code that is run through a web browser which interprets the code and displays all the pretty colors and pictures and stuff. Enough of with the theory.
To create a web page, you need 3 things. A text editor (to edit the code), a web browser (to interpret the code), and a language in which to write the code.
For the text editor, you can use MS Notepad (start->programs->accessories>notepad) and for the browser/interpreter, just use whatever browser you're using to view this page.
Modern webpages utilize a series of interconnected languages to provide the rich user experience we have today. The browser itself usually only interprets 3 of them: HTML, JavaScript, and CSS. Which brings me to an interesting aside.
In web programming, there are two different types of languages: Server-side and Client-side. The server is the big computer that the company will host the site on. You're computer, or the client, will contact the server and download the webpage which is then interpreted by your browser. Server-side scripts are run on the server, before your computer ever gets them. The Server-side script (written in Perl, or PHP, or C#, or Java ) will usually do some complex calculation or database interaction that your browser is unable to do. It creates a page with only Client-side code (javaScript, HTML, CSS) and sends THAT to your browser. Your browser interprets that code and displays the page. Because you only have access to the client (your computer and your web browser) we'll be focusing on Client-side languages.
A run down of the languages that we'll be covering:
HTML: HyperText Markup Language. This is the bread and butter of web sites. If you know nothing else, you can still make a decent web site that only uses HTML. It was originally designed to mark-up text in order to link pages together. Since then, it's been expanded to include formatting tools (bold, italic, tables, etc). HTML simply tells the browser how to render the page and does not provide much interactivity besides linking to other documents and pages. The current incarnation is called XHTML. It's more strict on syntax and adds more features but is, for the most part, still static.
CSS: Cascading Style Sheets. This language is used to make pages pretty. While it is possible to change colors and fonts and stuff using HTML, CSS allows us more options and freedom in regards to formatting and styling our pages.
javaScript: Or simply "JS". Not to be confused with Java (which is a compiled language that has absolutely nothing to do with javaScript). This language provides more interactivity with web pages. Plain HTML is very static. Adding javascript can make a page very dynamic. While it's pretty easy once you know the basics, it can be VERY powerful if you use it right.
--
That was clear as mud, right? I promise, it's easier than it sounds. Rather than putting you through a lot of computer science theory and trying to explain keywords and constructs and a lot of nonsense that I don't even know... I'm just going to drop it on you. You'll need to know a little HTML first, then we'll jump right into the javascript and all the fun stuff. We'll start simple and work our way up.
Now, open up notepad. First things first... Select File->Save As... from the menu bar. Change the "Save as Type:" to "All Files". This prevents notepad from adding ".txt" to the end of the filename. Name the file "index.html" (without the quotes) and save it to a place on your computer where you'll remember it (I usually save it on the desktop).
A long long time ago, someone decided that the default page of a website should be called "index.html". No one really knows why, but it's the standard. Sometimes, depending on where you host or what language you're programming in, the default name could be something like index.htm, index.php, default.html, default.aspx, or some other variation. You can name all the other pages of your site whatever you want, but the main landing page that the user first sees should always be one of those variations.
Enter the following code:
<html>
<head>
<title>My First Webpage</title>
</head>
<body>
Balls!
</body>
</html>
Save the file. Open a new window in your browser (File->New->Window or Ctrl+N). Open the file you just created in the browser (File->Open->Browse).
Now, what you should see is a page with the word "Balls!" displayed in the top left-hand corner and the words "My First Webpage" in the title bar.
Congratulations. You've created your first webpage.
Now for an explanation of what this code means. HTML is a "markup language" which means that you're basically putting tags around bits of text. The tags tell the browser what a piece of text is supposed to do or what it's supposed to look like. Bits of HTML can be nested in other bits of HTML. For example, the "head" chunk is nested in the "html" tags and the "title" bit is nested in the "head" tags.
The <html> tags must begin and end the web page. This tells the browser that the page is, indeed, an HTML page and should be interpreted as such.
The <head> section defines meta-data (data about the data) relating to the page. This section is not rendered (displayed) in the actual page. It tells the browser, and some other programs, interesting information about your page. This is where we will later add in the Style Sheets and the javaScript.
The <title> tags tell the browser what should be displayed in the title bar. Makes sense, right? Because this is not information that is to be displayed in the browser window, it belongs in the header section.
The <body> tags define the content (or body) of the page. This is the section that will actually be rendered in the browser. Right now, we've only got a small bit of text (Balls!) in there, but later on, we'll be adding all kinds of fun things like tables and lists and images.
There you have it. A simple page that demonstrates the (very) basics of web programming. The vast majority of HTML tags are named according to what they do in plain English. The <head> tags hold header information. The <body> tags hold the body of your page. And so forth.
Keep in mind that HTML tags must be closed. When you open a block of code with an opening tag (<body>), you have to end that block with the matching end tag (</body>). End tags are almost exactly the same as the beginning tag, except the tag name begins with a forward slash (/). Also, keep in mind that all tags must be properly nested. When a tag is nested within another tag, the inner tag must be closed before the outer tag. For example:
<head>
<title>My First Webpage
</head>
</title>
The above bit of code is incorrect. The title tag must be closed before the head tag. Incorrectly nested tags may cause errors and your page may not render properly.
Another thing to make note of is that HTML (as well as most other programming languages) ignores most white-space characters. White-space is the space between words including spaces, tabs, and line-breaks. For example:
<html>
<head>
<title>My First
Webpage</title>
</head>
<body>
Balls!
</body>
</html>
<html>
<head>
<title>
My First Webpage
</title>
</head>
<body>
Balls!
</body>
</html>
The above two pieces code will render EXACTLY the same as your original code. The indention of the original example is simply there to make the code more readable by humans. Computers really don't care. Anything after the first space after a word is completely ignored. The only thing to be careful about is that a space at the beginning of a tag will break the code. Example:
<html>
< head>
< title>My First Webpage< / title>
</head>
<body>
Balls!
< / body>
</ html>
The above code WILL NOT work correctly.
There are ways to reposition elements and add extra spaces and line breaks, but we'll get to that next time. If you're feeling ambitious, you can google HTML and learn about other tags to play around with. If you're not feeling so ambitious, I'll explain new tags as I get to them.
--
Well, that's it for now. I know this hasn't been very exciting, but the information presented in this article has hopefully provided you with the very basics of web programming. Next time, I'll introduce javascript which, I promise, will be a bit more exciting.
Until next time,
~~Ben
Saturday, November 17, 2007
AJAX redeux (now, with 20% less profanity and 100% less code)
What is AJAX?
AJAX stands for Asynchronous Javascript And XML. It’s really just a big complicated word that doesn’t really tell you anything about what it really is.
AJAX is a technique that allows a web page to communicate with a server without reloading the page. The key thing to remember is that it’s a TECHNIQUE. It’s a combination of existing technologies that work together to create a new and exciting result. There is nothing new to install on the server. There is nothing that the user needs to install, other than a web browser that supports javaScript.
To use AJAX you’ll need a few basic ingredients:
A web browser that supports javaScript
JavaScript
A web server
A server-side language of your choice (perl, php, c#, etc.)
JavaScript allows you to dynamically alter the layout and information of a page that is being displayed in the browser. “Dynamically” means that the changes happen in real time without having to reload the page. Everything happens on the client (in the browser). The problem is that the dynamicness is limited to the data that is already on the page, or the simple calculations that can be done in javaScript.
On the other hand, server-side languages allow powerful calculations and make it very easy to read and write data in databases and on the filesystem. Unfortunately, every call to the server requires you to reload and run the script. A typical server-side access happens as follows:
You click a button on the front end page. The browser redirects to the processing page as it submits the data to the server. The server sends the information back to the browser. The browser reloads with the new information. See figure A.
The trick with AJAX is to combine the best of both worlds through the use of a magical AJAX object. There are a couple of different kinds of magical AJAX objects. Some people use the javascript httpRequest object (in combination with an ActiveX control for Internet Explorer). Other people use standard HTML iFrames. Each has its own strengths and weaknesses. Which is better really depends on whom you’re talking to, but they all do the same thing.
AJAX requests happen as follows:
You click a button on the front-end page. The browser submits the request through the magic AJAX object. The server processes the back-end page inside the magic AJAX object. When the processing is done, the front-end page uses javaScript to grab the data from the magic AJAX object. The javaScript takes the data and adds it to the front-end page without ever having to reload. See figure B.
In conclusion, AJAX is a technique that utilizes the strengths of both dynamic client-side scripting (javaScript) and powerful server-side processing. Web applications that utilize AJAX are generally a great deal faster and increase the user experience tremendously. A user does something and the page responds accordingly, in real time. AJAX is an important part of any web developer’s toolbox. So stay armed with AJAX. It’s stronger than dirt.
Until next time,
~~Ben
Thursday, November 8, 2007
BenJAX (a.k.a. Really Fucked Up Pretend AJAX)
So, you've heard about this thing called AJAX and want to know more about it, eh? Well, I'm sure your first question is something like
"What the hell is AJAX, exactly?"
AJAX stands for Asynchronous Javascript And Xml. It’s a big, fancy, confusing word that really doesn’t mean a whole lot. It’s not a new programming language and there’s nothing new to install. All you need is javaScript, CSS and the server-side language of your choice.
The whole point of AJAX is to do server side stuff without having to reload the page you’re on.
Example:
Problem:
You have a list of users. Each user has a set of three checkboxes (permissions) for each user. You want to check or uncheck the boxes to set permissions. You need the permission to save as soon as you check/uncheck the box. You do not want to have to wait for the page to reload after every box click and then have to scroll down to where you were.
Solution:
You set an “onchange” event for each checkbox. When you change a checkbox, it calls the Save page in a separate process (asynchronously). The save page goes off and does its own thing, while you’re free to keep using the userlist page, not having to worry about it reloading on you.
Most AJAX tutorials suggest using some crazy ActiveX control or the new fangled httpRequest object. I’ve tried using all that and it never really works like I want it to. Recently, I’ve discovered that you can achieve the same effect using our good friend the iFrame.
In the past, iFrames were given lackluster support by browsers, so I always kind of avoided them. That was years ago, however. IE6+ and Firefox handle them just fine so I say use them.
IFrames act just like regular frames, except that they can be placed anywhere on a web page. And they can be styled using CSS. So, you can make them invisible. It’s a lot like magic.
I would imagine that this technique is not new, but since I just discovered its awesomeness, I’m going to refer to this as BenJAX, even though it should probably be called something along the lines of “iFrames that have been hacked to shit to emulate AJAX”.
The above example is very simple and only requires one-way communication. Up until today, I figured that would just be a (serious) limitation for BenJAX. This is definitely not the case.
Better Example:
Problem:
You have a text box that is going to be linked to a list journal names. You want to allow users to enter new names, but you also would like to guide them in order to avoid duplicates. It would be really nice if you could have them start typing something and a list pops up of all the journal names that start with what they were typing. (e.g. if they started typing “bal”, the list would pop up with “balls, balloons, balance, etc”). When they click on one of the items in the list, the text box should be populated with their selection.
Solution:
Add an “onKeyUp” event to the text box. Every time a user presses a key, a javascript function takes what’s in the text box and passes it a “ProcessTextbox” page through an invisible iFrame. The ProcessTextbox page returns a list of items for the user to select. Another Javascript function takes that information and sticks it into a list that the user can see and select from. Each item in that list has an “onClick” event that takes the item and puts it in the text box.
It’s a lot like magic. Unlike magic, I’m going to try to explain how I would do all that. Because I suck with .NET and you guys don’t know PHP, I’m just going to show you the javaScript. It’s going to be relatively simplified, but with any luck, it will get the point across.
You will need 2 different pages: a FormPage.aspx that will have your form with the text box and a ProcessTextbox.aspx page that will process the text box. The user is only going to see FormPage, but the meat of the processing will be done in ProcessTexbox. FormPage will utilize primarily client side scripting (javascript) while ProcessTextbox will be mostly server-side.
Here’s the code:
FormPage.aspx
<html>
<head>
<script type="text/javascript">
/*this function is called when a user presses a key in the textbox.
It calls ProcessTextbox.aspx with the query string search=searchText,
where searchText is the text in the textbox.
ProcessTextbox is processed on the server side and loads in the iFrame
named "magicFrame" where the user will never see it.
*/
callProcessTextbox = function (searchText)
{
frames["magicFrame"].location.href= "ProcessTextbox.aspx?search = "+searchText;
}
/* This function is called whenever the ProcessTextbox if finished loading in the magicFrame.
It takes the content of the "results" div from the ProcessTextbox and puts it in "resultList" div
in FormPage (this page).
The parameter frameContents is actually a reference to the window object of the magicFrame and can
pretty much be utilized the same way as the regular window object.
*/
magicFrameLoaded = function(frameContents)
{
document.getElementById("resultList").innerHTML = frameContents.document.getElementById("resultList").innerHTML;
}
/* This is called when user clicks on one of the items in the list. It takes that text and puts it into
the textbox.
*/
itemClick = function(itemText)
{
document.getElementById("journalTextBox").value = itemText;
}
</script>
</head>
<body>
...
<iFrame name="magicFrame" src="" style="display: none" ></iFrame>
<input type="text" onkeyup="callProcessTextbox(this.value)" id="journalTextBox" />
<div id="resultList"></div>
...
</body>
</html>
ProcessTextbox.aspx
The actual aspx/c# code could vary. It would be where you put the SQL Query and SQLServer call and process all the data. Example SQL Query might be: String Query = "SELECT * FROM [journal] WHERE [journalName] LIKE '%" + Response.QueryString["search"] + "%' "; In the end... assuming that the phrase "bal" was entered in the text box, the resulting html needs to look something like this:
<html>
<head>
<script type="text/javascript">
/* Called when this page is completely loaded. It simply passes the entire frame to
FormPage.aspx's magicFrameLoaded function
*/
window.onload= function()
{
parent.magicFrameLoaded(window);
}
</script>
</head>
<body>
<div id="resultList">
<ul>
<li onClick="itemClick(this.innerHTML)">balls</li>
<li onClick="itemClick(this.innerHTML)">balloons</li>
<li onClick="itemClick(this.innerHTML)">balance</li>
...
</ul>
</div>
</body>
</html>
Now, I have not tested this code. It's just an example. You'll need to tailor it to your specific needs. The processing page MUST have something like the window.onload function, or the FormPage won't know when it's loaded and won't know to get the resulting data.
IN THEORY, using AJAX, the process page is supposed to return some kind of XML structure. Then you use the javaScript to parse that XML and do stuff with it. That's why it's called Asynchronous Javascript and XML. Parsing an XML file isn't much more difficult than walking the DOM Tree, but I don't think it's essential for the kind of stuff we're doing. All we need to do is have the main page grab stuff from the iFrame with the processed page in it. I think it makes things easier to just use regular HTML in the processed page, letting the server-side script format all that good stuff.
I hope that made sense enough to help someone. I'm getting tired.
Until next time,
~~Ben
Saturday, November 3, 2007
All the Cool Kids Use Iframes
This is the 50th blog post here at the New Wisdom. Which is awesome. I'm actually sticking to my guns this time. I could use this post to rant about the future of the Wisdom, or vent about my day, but you're too good for that. Instead, I'll tell you about some awesome javascript stuff I learned at work.
A few days ago, I posted about some iframe hijinx. I used to loath iframes because of the major browsers' lackluster support of them. But that was a long time ago. I took a break from webmastering for a while in high school, and when I came back, everything was different. And iframes are awesome.
I had to make a windowed interface for this thing at work. Imagine a web based version of the Windows Explorer. I had to think for a while about how to implement this sucker. At first, I thought about using div layers and pure ajax. But that would be too hard and take too much time to figure out because I'm no pro with the ajax. Using layers without ajax would mean that everything would have to reload everything something changed. Lame. I could use a frame set. That would be ideal, except that it would be clunky and wouldn't fit into the templating thing I made.
Then I decided to harness the power of iframes. It was kind of a pain to get everything laid out right, but when I got that down, it was awesome. Now, if only I could do some javaScript in one iFrame and make the results show up in another. Turns out, javaScript's magical DOM support structure makes that fairly easy. The trick is, though, that you've got to name the iFrames. Take a look at this code here:
mainpage.html
<iframe name="topFrame" src="topFrame.html" />
<iframe name="bottomFrame" src="bottomFrame.html" />
<div id="output" ></div>
topFrame.html
<div id="topFrameOutput"></div>
bottomFrame.html
<script>
function changeOutput()
{
parent.document.getElementById("output").innerHTML = "NEW OUTPUT"; //this changes the output div of mainpage.html
parent.frames["topFrame"].document.getElementById("topFrameOutput").innerHTML = "NEW FRAME OUTPUT"; //this changes the output div of topframe.html
}
</script>
<a href="#" onclick="changeOutput()"> CLICK ME </a>
You've got a main page with two iframes and a div called "output". The top frame has a page with a div called "topFrameOutput". The page in the bottom frame defines a function called "changeOutput()" and a link that calls it. When you click the link, divs on both the main page and in the top frame will change. This makes cross frame scripting amazingly easy. But... lets say you want to call that "changeOutput" function from topFrame. Sure, you could redefine it. Or stick it in an external .js file. But that's no fun. Consider the following:
topFrame.html
<a href="#" onclick="parent.frames["bottomFrame"].document.changeOutput()"> CLICK ME </a>
<div id="topFrameOutput"></div>
bottomFrame.html
<script>
document.changeOutput = function()
{
parent.document.getElementById("output").innerHTML = "NEW OUTPUT"; //this changes the output div of mainpage.html
parent.frames["topFrame"].document.getElementById("topFrameOutput").innerHTML = "NEW FRAME OUTPUT"; //this changes the output div of topframe.html
}
</script>
<a href="#" onclick="changeOutput()"> CLICK ME </a>
What this does is add "changeOutput" as a method to bottomFrame's document. So, you can call it from topFrame as parent.frames["bottomFrame"].document.changeOutput(). I just kind of stumbled upon this today. I'm sure there's better ways to do it, but this works fine for me.
The more I play with it, the more I like it. Javascript is a really super powerful tool that every web programmer should have in his arsenal. The only problem is that not everything is 100% cross-browser, but as long as you hit the big 3 (IE6, FF, Safari) you should be fine. Have fun.
Until next time,
~~Ben
Saturday, October 27, 2007
AJAX ... Sorta
Today's mission, at work, was to implement some AJAX. I had this huge form that needed to be saved but not reload the page. AJAX should have handled that. Unfortunately, I don't know how to POST data with AJAX. After a while of browsing Google, I realized that AJAX POSTs were almost the same as AJAX GETs. You send the info via a string. Worse, however, is that PHP won't handle the the POSTed with $_POST or $_GET or anything like that.
I guess this wouldn't be bad if there wasn't so much data to be posting. Unfortunately, I would be posting this huge dynamically generated form. There was way too much data and way too little time to waste trying to code some AJAX. I was getting frustrated and asked Google what I should do. After a while, I came upon a few forum discussion somewhere that were really helpful.
Usually, when you submit a form, it will call the script and load it into the current browser window. Which is something I'm trying to avoid. Something I didn't know was that forms accept the target attribute. It works like a regular link, so if you wanted to have the submitted form load in a new window, you could do:
<form method="POST" action="script.php" target="_blank"></form>
As you may or may not know, the target tag can be used to target a frame when dealing with frame sets. Or iFrames. And iFrames can be manipulated by CSS. In fact, you can make them invisible. So, basically you're submitting a form to an invisible iFrame which reloads the iFrame and not the whole page. It's like magic:
<iframe name="submitFrame" src="" style="display: none"></iframe>
<form method="POST action="script.php" target="submitFrame"></form>
The only downfall is that you can't really any info back from the script. You can't have the script return an XML file or anything like that. So, it's pretty much only good for saving or deleting or something like that. Which is great for what I needed it to do.
I was dealing with a huge form, though. It might take a while to process, looping over quite a few records. Updating, Selecting, Manipulating. That sort of thing. It might be nice if I could update the user on the progress or at least tell them when it finished.
The best way I could think of was to not make the iFrame completely invisible. Just make it small enough. Or at least hide it until I needed to call it. The form processing script could echo "I'm finished" at the end and that would be visible to the user. In the end I had something like the following:
form.html:
<iframe name="submitframe" src="" style="width: 5em; height: 1em;">
<form name="someForm" method="POST" action="script.php" target="submitframe">
<input /> <input /> <input type="submit" />
</form>
script.php
<?php
$arrayOfStuff = $_POST["stuff"];
?>
<span id="status"></span>
<script type="text/javascript">
<?
for($k = 0; $k < count($arrayOfStuff); $k++)
{
DoSomeStuff();
?>
document.getElementById("status").innerHTML="<?= $k/count($arrayOfStuff) ?>%";
<?
}
?>
document.getElementById("status").innerHTML = "Done";
</script>
The form.html file contains the form and the iframe. No big surprise if you've been reading this. The iframe isn't not displayed. It's just sized so that it's not huge.
The script.php file gets an array that was posted to it. It spits out an empty span tag called "status" and starts a javascript. You put the script after the span so that it'll run as the php script runs. The span is already defined, so the javascript can use it as it goes. No need to define a function at the top and call it and all kinds of nonsense.
Then it loops over the array, doing whatever it is that you need to do. Wat each iteration, you spit out a line of javascript that changes the span to reflect the percentage that's been completed (the element you're at, divided by the total). When the loop is over, you spit out a final line that changes the span to say, "done" and close the script.
The user will see the script running in the iFrame, but the form.html page will not reload. Nice, easy and clean.
Of course, this is all super simplified so that it's easy for me to explain here. My actual code has lots of extras like alert boxes on errors: if there's an error in any iteration of the script, you could print out an 'alert("errormessage")' which will display a popup.
It's not a new idea, but I just discovered it and got super excited. It worked great. Did just what I wanted. Saved me a lot of time and code. I love it.
Until next time,
~~Ben
Tuesday, October 2, 2007
Blogger Hack
Yesterday, while making my daily post here, I realized one thing that my custom news poster has over Blogger: I can make custom tags. My news poster lets me put [URL]http://www.poonheads.com[/URL] and automatically makes it into a link. Yesterday, I had to write out the full HTML, which annoys me.
That got me thinking... I don't have any control over the server side of the app, so I can't add custom tags in there. But I *DO* have control over the client (or at least enough to make a difference). So I got to work with some javascript haxing.
I'm not too good with either javaScript OR regular expressions, but I make due. var pees = document.getElementsByTagName("p");
var RegExp = /\s(http[s]?:[/]+[\S]+)/g
for(var k = 0; k < pees.length; k++)
{
pees[k].innerHTML = pees[k].innerHTML.replace(RegExp, " $1");
}
The Blogger template gives me crap about malformed xml, so I crammed it into a .js and put it up on my server. It's at http://www.poonheads.com/replace.js . It's not 100%, but it gets the job done. Using the same principle (and a lot of wasted time making up regex's) I could probably hack up all kinds of stuff.
If I plan on doing a lot of code excerpts, I should probably hack up the <code> tag to display angle brackets and spaces. But I'm really lazy so I might not ever get around to it. Probably won't ever get around to it. But you never know.
So, do I get to call myself a javascript hacker yet? This counts, right?
Anyways, if you want more info on regex or javascript check out http://www.regular-expressions.info/ and http://www.w3schools.com/js/default.asp respectively.
Until next time,
~Ben
Monday, October 1, 2007
Of pngs and Feeds
I managed to shoe horn the RSS feed into the front page of Poonheads.com. You can get to it, by the way, by hitting the Home link in the menu there at the top of the page.
Now, this was a challenge for me. At work, I mostly use PHP and javaScript. In all my wisdom, however, I decided to program poonheads.com in C#.net 2.0. I hadn't touched the code in about a year and a half when I initially wrote it ( and it was fresh in my mind from my .Net programming class).
Originally, the main news post on the front page pulled from an XML page on my server. It was just a matter of changing the reference to the Blogger feed. And adjusting to the feed's new schema. Which sucked because my xml file is really simple and the blogger feed was very much not simple. So it took a lot of trial and error. I provide you now with the code. The secret was the InferSchema part. DataSet newsSet = new DataSet();
newsSet.ReadXml("http://poonheads.blogspot.com/feeds/posts/default", XmlReadMode.InferSchema);
DataRow newPost = newsSet.Tables["entry"].Rows[0];
lbl_title.Text = newsSet.Tables["title"].Rows[1][1].ToString();
lbl_poster.Text = newsSet.Tables["author"].Rows[1][0].ToString();
lbl_time.Text = newPost[1].ToString().Substring(0, 10);
String body_text = newsSet.Tables["summary"].Rows[0][1].ToString();
if (body_text.Length > 250)
{
body_text += "...";
}
a_continue.Text = "CONTINUE READING";
lbl_text.Text = body_text.Replace("\n", "<br />");
a_continue.NavigateUrl = newsSet.Tables["link"].Rows[3]["href"].ToString();
So, I don't know if that helps, but that's what it is. I don't feel like commenting or explaining it. I figure anyone who's looking at this probably knows kind of what's going on and would be able to figure it out.
I'm not really sure of a good way to display code in blogger. I'll probably just put some border around the <code>s with css. That ought to work good enough. Which brings me to my next point.
IE does not properly support .png alpha transparency. I've always known this, but never really bothered until I downloaded the RSS icon, which used alpha transparency. I didn't really want to mess with making another one, so I decided on just looking up an IE hack. I found a couple, but the results were kind of meh.
So I present to you the only foolproof 100% effective way to deal with alpha transparency in IE: Don't use alpha transparency in your pngs. Use indexed pngs or use gifs. Create your design without having to rely on transparency and everyone will be happy. The end.
So that's all I have for today. Except this random youtube video David showed me: http://www.youtube.com/watch?v=YgnloJgui1U
Until next time.
~~Ben