Welcome!

AJAX & REA Authors: John Funnell, Bob Little, Kevin Hoffman, Maureen O'Gara, Onkar Singh

Related Topics: AJAX & REA

AJAX & REA: Article

JavaScript Powers Up the Server Side

Be the envy of your Java, .NET, PHP, Perl, Python, and Ruby peers

You'll see that the example is written as a single HTML page with both the client logic and the server logic in the same HTML file (see Listing 1). You could easily move the JavaScript to another file and make it all unobtrusive, but here we'll just use an in-line script tag since the code is only about 30 lines long. Also note that there's no client-side JavaScript. We've done this on purpose so that the example can focus on a broad range of what can be done today on the server in JavaScript. (And, yes, of course you can have rich AJAX features on the client-side as well using Aptana Jaxer.)

Okay, let's get started. Our use case is the familiar blog or portal poll, where you are presented with a set of choices...

... and once you've voted you get to see the results.

One of the interesting features of this application is that by using server-side DOM manipulation in Jaxer you can remove any unwanted content before it's sent to the client browser. We use this to hide the vote results until the user has voted.

This is a useful technique for permission-based forms where, for example, you may want remove the credit card details unless the user has established the correct permissions and been validated by the server.

A Very Basic Web Page
So let's jump in and have a look at the code in Listing 2 that was used to make this work. Listing 2 shows the contents of the HEAD element. Just the usual suspects setting the title and some simple CSS stuff. The only interesting part is at line #3, where we load the jQuery library on the server, because we intend to do some server-side DOM manipulation before the page is sent to the client.

The runat=‘server' attribute tells Jaxer to load this JavaScript library on the server.

The autoload attribute is a recent addition to Jaxer, and it instructs Jaxer to load that page and keep it cached as pre-parsed bytecode (for a faster library load time) for any future calls to this page, including callbacks.

In the body of the document we have a simple form that we'll dynamically populate on the server. The form will post the vote to itself on the server.

We are marking up the DOM content with the class names ‘voter' and ‘nonvoter' to identify content specific to a user's status, and make it easily accessible using jQuery on the server.

<form id='pollContainer' method='POST' accept-charset='utf-8'>
<div id='question'>
What do you think is the coolest feature of Jaxer?
</div>
<div id='display'>
</div>
<div class='nonvoter'>
<input type='submit' value='vote'/>
</div>
<div id='voteTotals' class='voter'>
</div>

Server-Side JavaScript
Now we get to the JavaScript. The app has a single script tag in the body, which is designated to run on the server.

The first dozen or so lines are simply creating a DB and preparing a schema for use as shown in Listing 3. We've connected to the database (which was automatically created if needed, how convenient!) and set up the schema and initial content we expect. We also set up an Array (questions) containing the questions for the voting poll.

Next we need to check the session value we are storing (status) to determine whether this user has already voted, and then check to see if the form data for the vote is being posted. Then, if we are actually voting, we write the vote to the database and set the user status to ‘voter.'

When we write the vote to the database, we grab the sessionID and the remote IP address and write those out with the vote data; this will let us enforce single voting later if we need it.

Finally query the database to get the current vote counts, remembering to subtract 1 from the total to account for the dummy rows we inserted to seed the database and prevent any nulls from appearing in the results totals (see Listing 4).

Now we build the DOM. To do this we issue a query to the DB to get the current vote tally.

Using E4X-ECMAScript For XML as a simple templating tool we create the DOM with the nodes populated according to our dataset.

One of the nice features of server-side JavaScript with Jaxer is that you have access to all the neat things built into Mozilla without worrying about client-side browser support, which enables reliable use of the advanced features of the JavaScript language.

If you look closely at the code in Listing 5 you'll notice we use a simple syntax for variable substitution using curly braces containing JavaScript code inside the E4X assignments. This lets us use this for templating as long as we are creating valid XML nodes.

The document now has a DOM that's been populated with the content for BOTH voters and non-voters. We use a little jQuery magic to remove the elements we don't want presented to the user. In this way the user will EITHER see the form with the question and the submit button OR the current voting results data.

// remove DOM elements based on whether user has already voted
$((status == ‘voter') ? ‘.nonvoter' : ‘.voter').remove();

Now we set the session variable status to be the current status of the user as he has either voted or not. Finally as the page that's served has no further dependency on Jaxer once it leaves the server, we tell Jaxer not to bother injecting the client framework. Normally the client framework would be automatically inserted as a script tag in the outgoing HTML, but our simple example doesn't need to communicate back to the Jaxer server, since it contains no server callbacks.

// for the beta version of Jaxer, change the following line to
//Jaxer.session.set(‘status', status);
Jaxer.session.status = status;

// no need for the client Framework to be injected into the page.
Jaxer.response.setClientFramework();

So there you have it, a simple poll on a single page, using many of Jaxer's cool features.

Supporting Files
The full code and supporting files for this article are available at http://www.aptana.com/system/files/votepoll.zip.

More Stories By Kevin Hakman

Kevin Hakman is Director of Evangelism for Aptana, Inc., makers of the popular Aptana Studio web development suite. As early as 2001 Kevin was pioneering AJAX web applications via General Interface, a full AJAX development and GUI toolkit which he co-founded, and later sold to TIBCO Software in 2004. Kevin is a contributor to AJAXWorld Magazine, and has spoken at numerous AJAX industry events.

More Stories By Davey Waterson

Davey Waterson is a JavaScript architect at Aptana. He started out with Cobol coded on punch cards running on a Burroughs B1700 through to a DHTML Web UI using xhtmlRequest and Async Java. Davey has more than 20 years or experience as a code junky technophile and has worked in the industry in both Europe and North America.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.