In this section, we'll be taking a short tour of how we use JavaScript server-side within the Active Server Pages (ASP) environment. We'll see how to build pages dynamically as they are being loaded by the user, look at the various objects supported by ASP, and finally see how we can retrieve information posted to the server by a form on a web page.
Pages that contain server-side script stored on a Microsoft web server must be saved with the file extension .asp. The Microsoft servers (IIS) check only pages with .asp extension for server-side script, so if we put server-side script in a standard .htm or .html file, it will be ignored.
If we put it in an .asp page, the web server goes through each line in the page and executes any JavaScript marked for server-side execution before sending the page back to the browser. If our page is just an .htm or .html file, it is simply sent back to the browser without checks for any script that should be run server-side. If we have a page that doesn't contain server-side script, it's best to save it with an .htm or .html extension rather than an .asp extension, otherwise the server will spend valuable processing time checking for server-side script that is not there.
Although ASP files have a different file extension than HTML files, as far as web browsers are concerned they are just standard HTML pages containing HTML and client-side JavaScript. They are compatible with all web browsers. In fact, ASP scripting can help us with browser compatibility problems because it allows us to build up pages dynamically, and then send them to the browser as standard HTML without the problems of dynamic HTML browser support. For example, using ASP we can make sure that a different banner image is shown every time a page is viewed by the user and, because we're doing it server-side, it doesn't matter if the browser supports JavaScript and image replacement.
Let's take our first step by looking at how we can insert server-side script into a web page.
When we inserted client-side JavaScript, we didn't need to specify that the script language was JavaScript (although it is always good coding practice to do so); the browser's scripting language default was JavaScript. If we wanted to insert script in a different language, such as VBScript, we would have needed to specify that VBScript was the language we were using.
However, in server-side scripting in ASP, the default language is VBScript. If we don't specify the language, the server will process the script as VBScript and, of course, our JavaScript will cause errors.
Therefore, whenever we insert script server-side, we must specify that the language as JavaScript (although, in fact, it's Jscript, the Microsoft version of JavaScript). We can insert script and specify the language in one of two ways, which we will look at now.
The first way of inserting server-side script is using the same <script> tags we used for client-side JavaScript. However, we now need to specify the language using the language attribute and specify that the script is to be run at the server-side using the runat attribute.
<script language="JavaScript" runat=server> // Your server-side JavaScript here </script>
The second and preferred method of inserting server-side script is to tell the server which language is used for all server-side script on the current page by adding the following to the very first line of the page:
<%@ language = JavaScript%>
Then any server-script we add later in that page will be treated as JavaScript. (Note that this only counts for the current page; any other pages loaded must have their own language specifications.)
The <%@ %> code is unusual because it's actually designed to contain server directives. These are commands issued to the server itself. In this case, our directive to the server is that it treat all server-side code on the page as written in JavaScript, not VBScript. The directive must be on just one line by itself and at the top of the page.
Now, to add server-side script to the page we simply enclose it in <% and %>, which are called script delimiters.
<% // Your Server-side JavaScript here %>
One benefit of this second method of inserting server-side script is that we are able to write directly to the page by adding an equals sign to the first <% tag like this: <%=. For example, if we want to write the contents of a variable named myVariable to the page, we just write it as follows:
<%= myVariable %>
We can still use the following
<script language="JavaScript" runat=server> // Your server-side JavaScript here </script>
in pages where we have set the default language, but we must still tell IIS that it's JavaScript—we can't leave off the language attribute.
The core JavaScript language, that is, its syntax and its native objects, is the same server-side as it is client-side. For example, we have the same if statement, the for loop, the Math object, the String object, and so on.
However, the client-side script was being hosted (in other words, run) in a browser. This meant that we had access to the various objects that are made available in the BOM and are relevant to the browser. For example, we had the window object, the document object, and so on.
Server-side script is not being hosted in a browser, but is being run by the server and its environment. For this reason, instead of browser-related objects and the BOM, we have server-related objects and the ASP object model. Thus, when we are writing server-side script, we can't use the window object or the document object or, indeed, any of the BOM objects that a browser makes available. We'll see shortly what the new ASP object model contains and how we use that.
A second important point to make is that server-side script runs on one machine, the web server. Client-side script runs on a different machine, the one with the browser running. Script created server-side is not accessible to client-side script, and vice versa. For example, if we declared a variable or created a function in client-side script, we wouldn't be able to access that variable or function in server-side script. It can get confusing when you're running the browser and the server on the same computer, but they are still considered separate machines and no exchange is possible between the server and client sides.
We've seen how we can insert server-side script, so now let's use this to create our first server-side script program.
Let's create a page that loads a random banner image, from a choice of three, each time the user browses to it. In Chapter 9, we used three banner images called AdvertImage1.jpg, AdvertImage2.jpg, and AdvertImage3.jpg, so we may as well use these again.
<%@ language = JavaScript%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <% var randomAdvertNumber = parseInt(Math.random() * 3) + 1; var imgName = 'AdvertImage' + randomAdvertNumber + '.jpg'; %> </head> <body> <img src="<%= imgName %>"> </body> </html>
Save the file as BannerAdvert.asp. The file needs to be saved with an .asp extension, because we want the server-side script to be processed. Also, it needs to be placed under the root directory or subdirectory of the root directory of the server or in a directory that has been made into a virtual directory.
Here, I have placed the file in the physical directory C:\MyWeb sites\MyExampleDirectory that has the associated AWalkOnTheServerSide virtual directory, which I created in the previous section. I can then browse to the page using the following URL:
http://localhost/AWalkOnTheServerSide/BannerAdvert.asp
When loaded, the page randomly selects one of our three images, as shown in Figure 16-29.
Refresh the page a few times to see the random selection of the image.
At the very top of our page's code we have placed the following:
<%@ language = JavaScript%>
As we have seen, this tells the server that the language used for any scripts in this page is JavaScript. It's very important that this line is always the very first in the file and is on its own line with nothing else because it's a server directive.
Next, we have inserted two lines of JavaScript inside the head of the page. We've used <% to mark the start of the server-side script block and %> to mark its end. We can do this because we have already told the server that the language we are using for server-side script is JavaScript.
<head> <% var randomAdvertNumber = parseInt(Math.random() * 3) + 1; var imgName = 'AdvertImage' + randomAdvertNumber + '.jpg'; %> </head>
The code itself generates a random whole number between 1 and 3, and stores that in the variable randomAdvertNumber. Then it creates the name of the image stored in the variable imgName by appending the text AdvertImage to the start of the randomly created number, and the file extension, .jpg, to the end.
Finally, inside the body of the document, we define an <img> tag.
<img src="<%= imgName %>">
We can see that the src attribute of the <img> tag contains not the file name of an image, but some server-side script, the results of which will be inserted at that point in the page. The opening <% and closing %> mark the script block, and the equals sign (=) added to the <% causes the contents of the server-side JavaScript to be written out to the page. In this case, we are inserting the value of the variable imgName.
View the source for the page in the browser. To do this in Internet Explorer, choose Source from the View menu, and on Navigator choose Page Source from the View menu. You should see something similar to the following:
<html> <head> </head> <body> <img src="AdvertImage1.jpg"> </body> </html>
Note that all server-side script has disappeared. You'll also notice that it doesn't say
<img src="<%= imgName %>">
Rather, it contains the file name of the randomly selected image, which in this case looks like this:
<img src="AdvertImage1.jpg">
This is because all the script processing is done server-side. What is sent to the client's browser is the result of that processing, so the browser never gets to see our server-side JavaScript. This is a bonus if we don't want our script code to be shared with the world.
In server-side scripting, we can include HTML between JavaScript statements. For example, an if statement may start in one block of server-side JavaScript, but actually be closed in the following block of script, with the script blocks separated by HTML. Any HTML between the blocks will be affected by the if statement.
We can see this more clearly in the following example, which writes a heading to the page that tells whether a number contained in the variable myNumber is 101.
<% var myNumber = 101; if (myNumber == 101) { %> <h2>My Number was 101</h2> <% } else { %> <h2>My number was not 101</h2> <% } %>
At the top of the first script block, we've set myNumber to 101, so we know the outcome of the code already. However, what's important is that the following HTML, which is between the open curly brace of the if statement in the first block of JavaScript and its closing curly brace in the second block of JavaScript, will appear in the code sent to the client machine only if the condition of the if statement is true.
<h2>My Number was 101</h2>
In this case, the condition is myNumber == 101, so the heading will appear in the code.
The HTML between the open and close braces of the else statement won't be written out to the page, because the condition in the if statement was true. This is very different from client-side JavaScript where each script block must contain whole statements only.
This ability to use conditions to decide which blocks of HTML should be written to the final page and which should not is very powerful. We'll see later how we can detect which browser and operating system the user has. With this information, we could use an if statement to write only HTML to the page that is compatible with the user's browser.
In a similar way, loops, such as for and while, cause not only any JavaScript statements to be repeated, but also any HTML that might be inside the loop. In the following example, we repeatedly write a sentence containing a number that increments from 1 to 10.
<% var myNumber; for (myNumber = 1; myNumber <= 10; myNumber++) { %> <P> <STRONG>The Number this time is <%=myNumber%></STRONG> </P> <% } %>
Just as with the if statement, it's not only any JavaScript between the for loop's opening and closing braces that runs, but also the enclosed HTML is repeated each time the loop is repeated.