David Hurth's blog

Using JSON in Your Widgets

Tagged:  

Yesterday I posted an article on the del.icio.us Spy Widget. After writing the post I thought that other developers may be interested in how the communication was accomplished between the widget and the server. Since the browser stops cross-domain calls using the XMLHTTPRequest object (at least until Firefox 3 takes over the web) we have to turn to using JSON with a dynamic script tag.

So now that I've given a brief overview of how it will work let's get right down to the code. The below code would be used to dynamically create the script tag and load the JSON feed. Since the script tag does not have a cross-domain security restraint we can use it to load the feed from any domain.

var TimeStamp = new Date().getTime();
		var JSONCode=document.createElement("script");
       	JSONCode.setAttribute('type', 'text/javascript');
       	JSONCode.setAttribute("src", "http://someurl.com/somefeed.php?timestamp=" + TimeStamp);
        document.getElementById('codeholder').appendChild(JSONCode);

The important things to note in the above code is the timestamp variable passed in the URL and the codeholder DOM element. The timestamp variable is just a simple time stamp that is passed in the URL to prevent client side caching issues. In the URL is also where you would pass any additional variables to get the JSON feed. The codeholder DOM element (in the example code codeholder would be the id of the DOM element, but this could be a different id) is a DOM element that can hold a script tag such as a div tag.

Below we have an example of the JSON feed that would be received.

callbackfunction([{"title":"House of Marathon: A Very Brady Conservative","url":"http://houseofmarathon.blogspot.com/2008/01/very-brady-conservative-unlikeliest.html","tags":"BobbyJindal Louisiana RonaldReagan conservative ethics government health politics","user":"nathanm_mn"},{"title":"æ³¨æ„äº‹é …...請看這邊... - NoName Information Team XPE - Yahoo!å¥‡æ‘©éƒ¨è½æ ¼","url":"http://tw.myblog.yahoo.com/noname-team/article?mid=432&l=f&fid=9","tags":"XP","user":"square12"},{"title":"Retail-Menswear-Freemans Sporting Club - New York Times","url":"http://www.nytimes.com/2007/03/01/fashion/01CRITIC.html?_r=2&oref=slogin&oref=slogin","tags":"style","user":"MJDAOG"}]);

The important thing is that the feed has a call back function. This callback function could be named anything and is the JavaScript function that would be called to handle the JSON object.

The below code is an example of what a call back function might look like.

function callbackfunction(obj){
		alert(obj);
	}

In the above code the function would just display the object in an alert. This is where you would put the logic to go through the JSON object and then use it however you would like to in your application.

If you are using this in a widget you would have the user putting the widget on their site or blog copy and past some code and put it into the site or blog code. While you may have multiple lines of HTML for the user to copy you would need to have a script tag calling either a .JS file or a server side script that would produce dynamic JavaScript. The code that the script tag references would have the call back function and the portion of code that dynamically creates the script tag.

The above method allows you to create some more interactive widgets to make the web more interactive. While the above is all "hand rolled" code you can use many libraries to accomplish the dynamic creation of the script tag such as jQuery.

If you have ever created a widget that used this type of connection then I would love to hear about it. You can leave it in the comments or you can write a blog post with your free Ajaxonomy account.

del.icio.us Spy Widget Released

Tagged:  

You may have used our del.icio.us Spy application and hopefully it has been useful in finding new websites and bookmarks. If you have a blog or website you may have thought that it would be cool to have a widget of what is on the del.icio.us Spy. Well, we have just released a del.icio.us Spy widget for your blog or website.

Navigation Menus: Trends and Examples

Tagged:  

Over at Smashing Magazine they have posted a good article on navigation menu trends. The post does a good job of covering quite a few styles of navigation menus. I recommend this post if you are making a website or web application and are working on the navigation.

Below is an excerpt from the article.

Experimental solutions

Although it’s usually not the best idea to come up with some strange and/or unique site navigation, designers tend to risk crazy and uncommon experiments. When trying out something new, make sure that you don’t put the usability of your site in danger by creating unnecessary barriers for your visitors. Any navigation menu fails if users can’t make sense out of it.

DesignForFun uses icons to help visitors to filter the content they’re looking for. Depending on the clicked icon the background of corresponding links changes. However, the selection of icons may be not the best one as it’s unclear hat icons stand for. Fortunately, title attribute is in use.

Screenshot

Screenshot

Interesting concept: the hover-effect on jBunti depends on the selected month of the year. Warm months are associated with reddish colors, cold months with blueish colors. 12 hover-colors in use.

Screenshot

Playground Blues tries out something completely different; each of 12 site sections has its color in the left sidebar. Once the visitor hovers the mouse arrow over the left-hand sidebar the icons pop up providing visitors with navigation options. Title-attribute is used as well. And to make sure visitors actually can find the navigation the icons pop out like harmonica first time the page is loaded.

Screenshot

Steven Holl is an architect. Which is why his navigation menu looks like an architectural sketch. Each navigation option is given some weight in the map — apparently according to its weight on the site.

Screenshot

Polkdesign uses a calender as the central navigation element. Flash.

Screenshot

Hopkingdesign offers not a tabbed-navigation; it’s a vertical navigation placed at the top of the page. Looks at least unusual.

Screenshot

No, Adipintilie.eu has navigation options also placed at the top; however, these are only external links.

Screenshot

Flash-based 3D-effect used on Gol.com.pl. The menu can also be expanded.

Screenshot

The navigation on Wards-Exchange.co.uk fits to the brochure design. Or the other way around.

Screenshot

On Kriesi.at the hovered navigation option is dynamically expanded and shows the icons which illustrate what to expect in the section of the site. The effect is in this case not necessary.

Screenshot

Not really new, but still beautiful. Folietto.at uses the free area effectively and sparingly. You may notice an interesting visual effect when hovering the links.

Screenshot

inBloom has a menu with animation. The beetle doesn’t care what option you choose, it crawls its long path through the navigation tree anyway. This is an example of how animation can be unobtrusive.

Screenshot

Cobahair.co.uk uses only BIG typography…

Screenshot

…and HelloColor.com uses small typography with rainbow colors.

Screenshot

Carbonstudio.co.uk delivers a Flash-based navigation menu with sound-effects. It may sound annoying, but it isn’t: every navigation option has its own sound. If you train yourself a little bit you can even play your own melody while listening to birds in the background.

Screenshot

Maxandlous.com provides hover-effects with visual hints. It looks nice and unusual.

Screenshot

Scrollomania in all possible directions on Letters-Numbers.com.

Screenshot

OK, how can you come up with this one? Nickad’s Flash-based construct becomes visible only if the mouse is clicked and remains being clicked.

Screenshot

Nike offers a kind of remote control. To navigate you need to click and drag. While dragging, move the mouse up to move forward, down to move backward, and left/right to turn.

You can read the full post here.

I think it is always good to see what trends are going on in the web as it can give you good ideas for your own development. If you use any of the techniques in this post I would love to hear about them, you can either leave them in the comments or write a full blog post about them on this blog with your free Ajaxonomy account.

Upload Files Asynchronously

Tagged:  

You are familiar with Ajax and I'm sure that you've used it (or seen it used) in many applications. Of course Ajax is used to transfer data through XML or JSON (or plain text) so the data is never binary data. However, what if you are making an application that needs to be able to upload a binary file asynchronously? Well I've run across an interesting article that explains how to accomplish this.

The article has updated code from the initially released code. Below is the initial code.

Source code for index.html   (Download source code)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Iframe Ajax</title>
    <script type="text/javascript" src="webtoolkit.aim.js"></script>

    <script type="text/javascript">
        function startCallback() {
            // make something useful before submit (onStart)
            return true;
        }

        function completeCallback(response) {
            // make something useful after (onComplete)
            document.getElementById('nr').innerHTML = parseInt(document.getElementById('nr').innerHTML) + 1;
            document.getElementById('r').innerHTML = response;

        }
    </script>
</head>

<body>

    <form action="index.php" method="post" onsubmit="return AIM.submit(this, {'onStart' : startCallback, 'onComplete' : completeCallback})">

        <div><label>Name:</label> <input type="text" name="form[name]" /></div>
        <div><label>File:</label> <input type="file" name="form[file]" /></div>

        <div><input type="submit" value="SUBMIT" /></div>
    </form>

    <hr/>

    <div># of submited forms: <span id="nr">0</span></div>

    <div>last submit response (generated by form action - index.php file): <pre id="r"></pre></div>

</body>
</html>

Source code for webtoolkit.aim.js   (Download source code)

/**
*
*  AJAX IFRAME METHOD (AIM)
*  http://www.webtoolkit.info/
*
**/

AIM = {

    frame : function(c) {

        var n = 'f' + Math.floor(Math.random() * 99999);
        var d = document.createElement('DIV');

        d.innerHTML = '<iframe style="display:none" src="about:blank" id="'+n+'" name="'+n+'" onload="AIM.loaded(\''+n+'\')"></iframe>';

        document.body.appendChild(d);

        var i = document.getElementById(n);
        if (c && typeof(c.onComplete) == 'function') {
            i.onComplete = c.onComplete;
        }

        return n;
    },

    form : function(f, name) {
        f.setAttribute('target', name);
    },

    submit : function(f, c) {

        AIM.form(f, AIM.frame(c));
        if (c && typeof(c.onStart) == 'function') {
            return c.onStart();
        } else {
            return true;
        }
    },

    loaded : function(id) {
        var i = document.getElementById(id);
        if (i.contentDocument) {
            var d = i.contentDocument;
        } else if (i.contentWindow) {
            var d = i.contentWindow.document;

        } else {
            var d = window.frames[id].document;
        }
        if (d.location.href == "about:blank") {
            return;
        }

        if (typeof(i.onComplete) == 'function') {
            i.onComplete(d.body.innerHTML);
        }
    }

}

You can see the demo of the code here.

Below is an excerpt (including the code) from the updated post.

How to upload files asynchronously?

As I described above You can’t upload files using AJAX. Some time ago I wrote a JavaScript file upload object which as You already understood can help developers make forms which upload files asynchronously.

Today I made some modifications to this code and I want You to try it. Its simple, really fast to implement. Just paste this code into your document or external JavaScript (ajaxupload.js) file:

AsyncUpload = {
 
	createFrame : function(formElement, completeCallback) {
		var frameName = 'f' + Math.floor(Math.random() * 99999);
		var divElement = document.createElement('DIV');
		divElement.innerHTML = '<iframe style="display:none" src="about:blank" id="'+frameName+'" name="'+frameName+'" onload="AsyncUpload.documentLoaded(\''+frameName+'\')"></iframe>';
		document.body.appendChild(divElement);

 
		var frameElement = document.getElementById(frameName);
		if (completeCallback && typeof(completeCallback) == 'function') {

			frameElement.completeCallback = completeCallback;
		}
		formElement.setAttribute('target', frameName);
	},
 
	documentLoaded : function(elementID) {

		var frameElement = document.getElementById(elementID);
		if (frameElement.contentDocument) {
			var documentElement = frameElement.contentDocument;
		} else if (frameElement.contentWindow) {

			var documentElement = frameElement.contentWindow.document;
		} else {
			var documentElement = window.frames[elementID].document;
		}

		if (documentElement.location.href == "about:blank") {
			return;
        }
		if (typeof(frameElement.completeCallback) == 'function') {

			frameElement.completeCallback(documentElement.body.innerHTML);
		}
	},
 
	submitForm : function(formElement, startCallback, completeCallback) {

		AsyncUpload.createFrame(formElement, completeCallback);
		if (startCallback && typeof(startCallback) == 'function') {
			return startCallback();
		} else {

			return true;
		}
	}
 
}

Now write your xHTML document (index.html). Let say it will look like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

    <title>Asynchronous Upload</title>
    <script type="text/javascript" src="ajaxupload.js"></script>

    <script type="text/javascript">
        function startCallback() {
            return true;
        }
 
        function completeCallback(response) {
            obj = eval('('+response+')');
            alert(obj.firstname);
            document.getElementById('r').innerHTML = response;
        }
    </script>
</head>
 

<body>
 
    <form action="index.php" method="post" enctype="multipart/form-data" onsubmit="return AsyncUpload.submitForm(this, startCallback, completeCallback)">

        <div><label>First name:</label> <input type="text" name="firstname" /></div>

        <div><label>Last name:</label> <input type="text" name="lastname" /></div>

        <div><label>CV:</label> <input type="file" name="cv" /></div>

        <div><input type="submit" value="SUBMIT" /></div>
    </form>

 
    <p>Response: <span id="r"></span></p>
 
</body>
</html>

On backend (web server) i wrote this PHP script (index.php):

<?php
echo json_encode(
	array_merge(
		$_REQUEST,
		$_FILES

	)
);
?>

Now You must fill the form (firstname, lastname and attach CV file) to test it. When You submit the form, the current page won’t reload. This script will load the index.php file in the background (CV file will be sent in the background too). PHP script will output JSON (about this technology maybe some other time) encoded string.

In the index.html file function completeCallback will handle the index.php response without reloading the page. Voila! Now You only need to figure it out where You can use this JavaScript Asynchronous File Upload Object.

You can read the full post here.

You can download the full source code here.

This is a very interesting use of sending data asynchronously. I never would have thought to use frames in the way that the code does in order to upload the file. I would love to hear if you find any good uses for this code. You can leave them in the comments or write a complete blog post on this blog using your free Ajaxonomy account.

The initial source code was originally posted on webtoolkit.info

A Teris Game in JavaFX

Tagged:  

Like many developers I got into software development because I wanted to make games. While I don't work on game development anymore I still have an interest in the development, especially as it has to do with the web. Well over at DZone's JavaLoby Jim Weaver has posted an interesting article about making a Tetris game using JavaFX. This is the first post in a series of posts that will take you through the development of the game.

Below is an excerpt from the post.

In Tetris, there are several types of tetrominoes, each having a letter that it resembles. The four buttons on the left represent four of these shapes. When you press one of these buttons, the corresponding tetromino appears at the top and begins moving down the screen. When you click the Rotate button, the tetromino rotates to the right, and the Left/Right buttons move the tetromino left and right, respectively.

The code is contained in four FX program files, and needs some refactoring already. :-) Before showing you the code in its current state, I'd like to point out a couple of helpful things:

  • As explained in the Spinning Wheel post, the Key Frame animation syntax that you see here will become much less verbose as the JavaFX Script compiler team continues to address animation.
  • JavaFX Script programs should always be designed with the UI binding to a model. In this program, the model is represented in one class named TetrisModel, located in the FX file of the same name. You may find it helpful to take a look the Creating a Compiled JavaFX Script Program with Multiple FX Source Files post to see a Hello World style program that has more than one FX file. Please notice the package statments in this Tetris program, as that influences where you need to put the source files and how you build them.
  • You can obtain the JavaFX Compiler by following the instructions in the Obtaining the OpenJFX Script Compiler post.

The Source Code (so far)

Here's the main program, named TetrisMain.fx, that declaratively expresses the UI, and starts things up:

/*
* TetrisMain.fx - The main program for a compiled JavaFX Script Tetris game
*
* Developed 2008 by James L. Weaver (jim.weaver at lat-inc.com)
* to serve as a compiled JavaFX Script example.
*/
package tetris_ui;

import javafx.ui.*;
import javafx.ui.canvas.*;
import java.lang.System;
import tetris_model.*;

Frame {
var model =
TetrisModel {

}
var canvas:Canvas
width: 480
height: 500
title: "TetrisJFX"
background: Color.WHITE
content:
BorderPanel {
center:
canvas = Canvas {}
bottom:
FlowPanel {
content: [
Button {
text: "I"
action:
function() {
canvas.content = [];
insert
TetrisShape {
model: model
shapeType: TetrisShapeType.I
}
into canvas.content;
model.t.start();
}
},
Button {
text: "T"
action:
function() {
canvas.content = [];
insert
TetrisShape {
model: model
shapeType: TetrisShapeType.T
}
into canvas.content;
model.t.start();
}
},
Button {
text: "L"
action:
function() {
canvas.content = [];
insert
TetrisShape {
model: model
shapeType: TetrisShapeType.L
}
into canvas.content;
model.t.start();
}
},
Button {
text: "S"
action:
function() {
canvas.content = [];
insert
TetrisShape {
model: model
shapeType: TetrisShapeType.S
}
into canvas.content;
model.t.start();
}
},
Button {
text: "Rotate"
action:
function() {
model.rotate90();
}
},
Button {
text: "Left"
action:
function() {
model.moveLeft();
}
},
Button {
text: "Right"
action:
function() {
model.moveRight();
}
}
]
}
}
visible: true
onClose:
function():Void {
System.exit(0);
}
}

 

I made the TetrisShape class a custom graphical component. Therefore, it is a subclass of the CompositeNode class, and overrides the composeNode function:

/*
* TetrisShape.fx - A Tetris piece, configurable to the
* different shape types. They are:
* I, J, L, O, S, T, and Z
*
* Developed 2008 by James L. Weaver (jim.weaver at lat-inc.com)
* to serve as a compiled JavaFX Script example.
*
*/
package tetris_ui;

import javafx.ui.*;
import javafx.ui.canvas.*;
import java.awt.Point;
import java.lang.System;
import tetris_model.*;

class TetrisShape extends CompositeNode {
private static attribute squareOutlineColor = Color.BLACK;
private static attribute squareOutlineWidth = 2;
private attribute squareColor;

public attribute model:TetrisModel;
public attribute shapeType:TetrisShapeType on replace {
if (shapeType == TetrisShapeType.I) {
squareLocs = [];
insert new Point(0, model.SQUARE_SIZE * 1) into squareLocs;
insert new Point(0, 0) into squareLocs;
insert new Point(0, model.SQUARE_SIZE * 2) into squareLocs;
insert new Point(0, model.SQUARE_SIZE * 3) into squareLocs;
squareColor = Color.RED;
}
else if (shapeType == TetrisShapeType.T) {
squareLocs = [];
insert new Point(model.SQUARE_SIZE * 1, 0) into squareLocs;
insert new Point(0, 0) into squareLocs;
insert new Point(model.SQUARE_SIZE * 2, 0) into squareLocs;
insert new Point(model.SQUARE_SIZE * 1, model.SQUARE_SIZE * 1) into squareLocs;
squareColor = Color.GREEN;
}
else if (shapeType == TetrisShapeType.L) {
squareLocs = [];
insert new Point(0, model.SQUARE_SIZE * 1) into squareLocs;
insert new Point(0, 0) into squareLocs;
insert new Point(0, model.SQUARE_SIZE * 2) into squareLocs;
insert new Point(model.SQUARE_SIZE * 1, model.SQUARE_SIZE * 2) into squareLocs;
squareColor = Color.MAGENTA;
}
else if (shapeType == TetrisShapeType.S) {
squareLocs = [];
insert new Point(model.SQUARE_SIZE * 1, 0) into squareLocs;
insert new Point(model.SQUARE_SIZE * 2, 0) into squareLocs;
insert new Point(0, model.SQUARE_SIZE * 1) into squareLocs;
insert new Point(model.SQUARE_SIZE * 1, model.SQUARE_SIZE * 1) into squareLocs;
squareColor = Color.CYAN;
}
}

private attribute squareLocs:Point[];

public function composeNode():Node {
return
Group {
transform: bind [
Translate.translate(model.SQUARE_SIZE * model.tetrominoHorzPos,
(model.a / model.SQUARE_SIZE).intValue() * model.SQUARE_SIZE),
Rotate.rotate(model.tetrominoAngle,
squareLocs[0].x + model.SQUARE_SIZE / 2,
squareLocs[0].y + model.SQUARE_SIZE / 2)
]
content: [
for (squareLoc in squareLocs) {
Rect {
x: bind squareLoc.x
y: bind squareLoc.y
width: bind model.SQUARE_SIZE
height: bind model.SQUARE_SIZE
fill: bind squareColor
stroke: squareOutlineColor
strokeWidth: squareOutlineWidth
}
}
]
};
}
}

 

The TetrisShapeType class defines the tetromino types:

/*
* TetrisShapeType.fx - A Tetris shape type, which are
* I, J, L, O, S, T, and Z
*
* Developed 2008 by James L. Weaver (jim.weaver at lat-inc.com)
* to serve as a compiled JavaFX Script example.
*
*/
package tetris_ui;

import javafx.ui.*;

class TetrisShapeType {
public attribute id: Integer;
public attribute name: String;

public static attribute O =
TetrisShapeType {id: 0, name: "O"};
public static attribute I =
TetrisShapeType {id: 1, name: "I"};
public static attribute T =
TetrisShapeType {id: 2, name: "T"};
public static attribute L =
TetrisShapeType {id: 3, name: "L"};
public static attribute S =
TetrisShapeType {id: 4, name: "S"};
}

 

And finally, here's a model class, named TetrisModel:

/*
* TetrisModel.fx - The model behind the Tetris UI
*
* Developed 2008 by James L. Weaver (jim.weaver at lat-inc.com)
* to serve as a compiled JavaFX Script example.
*
*/
package tetris_model;

import javafx.ui.animation.*;
import java.lang.System;
import com.sun.javafx.runtime.PointerFactory;

public class TetrisModel {
public static attribute SQUARE_SIZE = 20;

public attribute a:Integer;
private attribute pf = PointerFactory {};
private attribute bpa = bind pf.make(a);
private attribute pa = bpa.unwrap();
private attribute interpolate = NumberValue.LINEAR;
public attribute t =
Timeline {
keyFrames: [
KeyFrame {
keyTime: 0s;
keyValues:
NumberValue {
target: pa;
value: 0;
interpolate: bind interpolate
}
},
KeyFrame {
keyTime: 20s;
keyValues:
NumberValue {
target: pa;
value: 370
interpolate: bind interpolate
}
}
]
};
public attribute tetrominoAngle:Number;
public attribute tetrominoHorzPos:Number = 10;

public function rotate90():Void {
(tetrominoAngle += 90) % 360;
}

public function moveLeft():Void {
if (tetrominoHorzPos > 0) {
tetrominoHorzPos--;
}
}

public function moveRight():Void {
if (tetrominoHorzPos < 20) { //TODO:Replace 10 with a calculated number
tetrominoHorzPos++;
}
}
}

 

You can read the full post here.

This use of JavaFX is very interesting, I'm looking forward to reading Jim's next post.

AdSense for Video now in Beta

Tagged:  

We've been hearing that it was coming, but Google's AdSense for Video is finally released in beta form. People will now be able to easily advertise on their YouTube videos.

Below is an excerpt regarding the release from the Official Google blog.

Enter, stage left: the AdSense for video beta. This approach takes the same non-intrusive InVideo ad format used on YouTube and extends it across video partner sites on the Google Content Network. This enables advertisers to run a single campaign across the largest network of online video content.

Unique to AdSense for video are text overlay ads contextually targeted to a combination of signals in your videos and on your site. With these overlay ads, the user's experience is not interrupted; users determine how much they want to interact with the ad.

We have two major goals: to make it easier for publishers to monetize video online, and for advertisers to learn how to reach the video community. Towards these ends, today we're also launching a single destination with an overview of various options to expand online video opportunities called Google Video Advertising Solutions. We hope this will be your starting point to understand how to leverage the Google Content Network and YouTube to make the most out of the online video experience. You can also see our overview videos for advertisers and publishers -- because isn’t video the best way to experience video?

We've been working with a number of video partners (e.g. popular destinations like BobVila.com, eHow, MyDamnChannel, ExpertVillage, PinkBike, TheNewsRoom, and social video aggregators like Revver, blip.tv, and GodTube). And we're also working with several key video platform solution solutions like Brightcove, Yume, Tremor Media, and Eyespot Network, who have plugged our ads into their platforms.

There are some criteria that publishers have to meet to participate in AdSense for video, which you can learn about on the Inside AdSense blog.

You can read the full post here.

The thing that sounds very interesting is how the ads will be placed in the video. This will be very interesting to see in action. It am looking forward to seeing how this catches on and if popular videos start making decent money.

From Google's stand point it is a great way to increase their ad revenue as they already have a strong hold on sites like this blog (look at the ads on the right hand side of this page). It is possible that with Google's purchase of FeedBurner that they could rule that ad space in Web Sites/Blogs, RSS Feeds and On-line Videos.

Creating a Simple JavaScript Game Board

Over at the Web Cash blog they have posted two tutorials on Game development in JavaScript, Ajax and PHP. The first tutorial explains the concept and describes how to make a game board.

Below is an excerpt from the first tutorial.

Game Development with JS, AJAX, and PHP

How can we use JS and PHP - connected through AJAX - to develop an online game?

Javascript’s main use for us is to create an interface for the game. Through Javascript we can capture user input - i.e. mouse clicks and text. We can also alter the game’s output - changing the HTML of the page, adding images, and moving things around. Javascript will provide a lot of the front end work.

PHP, on the other hand, is a more robust language for dealing with the logic of the game. PHP could be useful for developing an AI and evaluating winning conditions. It also offers a great way to store information for later use through flat files or database integration.

If we’re going to use both Javascript and PHP, we’ll need to use AJAX. This is the glue that holds the whole thing together. It will send input from the main Javascript to the PHP processing scripts. The PHP script will then send info back to the Javascript and it will alter the page’s layout accordingly.

Read the full first tutorial here.

The second tutorial goes into more detail as to how you would start creating a simple game. By the end of the tutorial you have a complete simple tic-tac-toe game (the game needs more logic added to be finished, but the concept is there).

Below is an excerpt from the second tutorial.

Creating Graphics

Tic Tac Toe Circle ImageI created two images in Inkscape to use for this board. Each is a 50×50 png file - with a gray background and a black border. The actual token (the circle or cross) is red and laid on top of the gray background.

Tic Tac Toe Cross ImageI’m no great artist, but these should work for a functional demo. We can worry about making nice circle and cross tokens later. I think getting the game working is more important than making it pretty from the get-go.

Turning Our .js Script into a Class

In making this a functional board, I also converted the script into an actual class. The script may end up being somewhat large and unwieldy - and an object oriented approach may help us keep it tidy and clean. Or it may add a lot of overhead… but I like objects.

In our HTML file, we’ll create the object like this.

<script type="text/javascript">
var tictactoe = new game();
</script>

In the attached .js file, we actually define the game object. Here’s part of the object definition.

function game() {
  //  Array to hold the bgImgs
  this.bgImgs = new Array();
    this.bgImgs[0] = 'tttcircle.png';
    this.bgImgs[1] = 'tttcross.png';

 
  //  Player information			
  this.currentPlayer = 0;
  this.players = new Array();
    this.players[0] = "Player One";
    this.players[1] = "Player Two";

 
   return true;

This class constructor does some of the initialization for us.

First, it creates an array with background images. At the moment we’re only using two images. However, this technique would be useful if you had a more complex map - with 10-15 images you could lay over a div.

Second, we create some player information variables. The ‘currentPlayer’ property is going to track whether the ‘cross’ or ‘circle’ player is currently taking a turn. The ‘players’ array will just hold the names of those players for now.

The Background Image Changing Function

One of the major methods of this class will be changeBackground(). Just like in the previous example, this method will change the background style of a given div tag. This way we can change it from an open square to a circle or cross token.

  this.changeBackground = function (boxId) {
    var box = document.getElementById('box-' + boxId);
    box.style.background = 'transparent url(' + 
      this.bgImgs[this.currentPlayer] + ') top left no-repeat';

 
    box.removeAttribute('onClick');
 
    this.changePlayer();
  }

This should be pretty straightforward. We’re storing the ‘div’ element in the ‘box’ variable. We’re then setting the ‘background’ style as we would in a css style. Remember that we stored the background images in an array (this.bgImgs) and this.currentPlayer corresponds to a key in the this.bgImgs array (either 0 or 1).

The ‘box.removeAttribute()’ method is removing ‘onClick’ from that div. We can’t use a square a second time, so we might as well eliminate the onClick handler altogether.

Finally, this.changePlayer() is calling a new method. This is going to help us switch from Player One’s turn to Player Two’s turn.

One Turn to Another - this.changePlayer()

The last method we need to declare for this class at the moment is changePlayer.

This will toggle the active player - which in turn affects whether a circle or cross is placed on the board. For some added effect, we’ll also create a new html element to display a message that says who’s turn it is.

  this.changePlayer = function () {
    //  Switch the active player

    if (this.currentPlayer == 0) {
      this.currentPlayer = 1;
    } else {

      this.currentPlayer = 0;
    }
 
    //  Get a reference to our 'message' element and create the message
    var box = document.getElementById('message');
    var msg = "It is " + this.players[this.currentPlayer] + "'s turn.";
    var txt = document.createTextNode(msg);

 
    //  Erase any existing text
    while (box.hasChildNodes()) {
      box.removeChild(box.lastChild);
    }

 
    //  Add the text node (our message) to our element
    box.appendChild(txt);
  }

Again, this is pretty straightforward. The DOM functions are amazingly simple - once you see how they work.

‘box’ is a reference to our element (id = message). The msg variable is a temp variable I created to hold the string. The ‘createTextNode’ method creates a new block of text (with our msg) that we can then insert into an HTML element.

The while() loop is simply there to erase any old text. As long as our ‘box’ element has any child nodes inside of it (text or other HTML tags), the loop will execute and delete one of those child nodes each time. This way we have a clean slate on which to write down who’s turn it is.

Read the full second tutorial here.

Although the tutorial only shows a simplistic tic-tac-toe game you could use the concepts as a starting point to build your own web games. As always if you have made any cool games we would love to hear about them either in the comments or you can write a blog post about it using your free Ajaxonomy account.

Help Your Site Users with a Step By Step Tour

Tagged:  

Have you ever made an incredible web application that you think is very intuitive to users, just to be told by a friend or user that they couldn't figure it out? Often our knowledge of our applications blinds us to the fact that everything may not be as simple to use as we thought.

Because of this common problem Christian Heilmann has written a good solution to the problem called Step by Step. The script displays a sort of tool tip that walks you through a site step by step.

Below is how the script is explained by Chris.

You might have encountered interactive demos created with screencasting and screengrabbing software that explain an interface to users in a step-by-step manner. This is exactly what this script does for web sites.

When you loaded this page and all went well you'll have seen the examples, download and first paragraph section being highlighted and a small panel with information showing up in succession. This is done with this script.

The script uses the Yahoo! User Interface (yet another good example of the library) for the effects, so it does have that dependency.

You can go to the official website here and you can download the code and examples here. To view the examples click here.

If you use this or any other similar script I would love to hear about them. You can leave them in the comments or write a post about them on this blog using your free Ajaxonomy account.

Ajax Security

Tagged:  

Over at Reg Developer they have posted a good article regarding Ajax security. The article takes a 1-2-3 approach to security and covers topics like cross site scripting and SQL injection.

Below is an excerpt from the article.

Know what runs where

AJAX is making it increasingly difficult to be sure where your code is going to run. Take the Google Web Toolkit (GWT) for example. You program in Java and the environment takes some of that code and compiles it to JavaScript that runs on the client. If you make a mistake and implement authentication, access control, validation, or other security checks in the code that runs on the client, an attacker can simply bypass them with Firebug.

Imagine you've carefully coded rules to be sure that administrative functions are never shown to ordinary users. This sounds good, but you forgot that the user interface code is running on the client. So the attacker uses Firebug to invoke the administrative functions. If the proper checks aren't in place on the server side, the attacker just gained administrative rights. Many Rich Internet Application (RIA) frameworks also have this issue.

The solution is to be very careful about making the boundary between the client and the server very clear.

Keep data separate from code

Hackers frequently use a technique called "injection" to bury commands inside innocent-looking data and get interpreters to execute their commands for them. This simple trick is at the heart of many security attacks including SQL injection, command injection, LDAP injection, XSS, and buffer overflows. Preventing injection in a target-rich environment like the modern browser takes discipline.

The key to stopping injection attacks is never executing data that might contain code. But with AJAX, lots of data and code get passed around and mashed together in the DOM. There has never been a data structure that mixes together code and data more than modern HTML.

So be very careful with data that might include user input. Assume it's an attack unless you've carefully canonicalized, validated, and properly encoded. Imagine you're invoking a REST interface and the request contains user data. The response you receive is a JSON string that includes that user data. Don't evaluate that string until you're sure that there can't be anything but safe data in there. Even just adding that data to the DOM might be enough to get it to execute if there's JavaScript code buried in there.

Beware encoding

Encoding makes everything complicated. Attackers can hide their attacks inside innocent-looking data by encoding it. Back-end systems may recognize the encoding used and execute the attack. Or they may decode the attack and pass it on to a system that's vulnerable to it.

Attackers may use multiple different encoding schemes, or even double encode to tunnel their attacks through innocent systems. There are dozens and dozens of encoding schemes and no way to tell which schemes will be recognized by the interpreters you're using. This makes recognizing attacks very difficult, if not impossible.

Every time you send or receive data both sides have to know the intended encoding. Never try to make a "best effort" attempt to guess the right encoding. You can't prevent an attacker from sending data with some other encoding through the channel, but you don't have to execute it. Here are a few examples:

Set HTTP encoding in the header:

 
   Content-Type: text/xml, charset=utf-8

Use a meta tag in the HTML:


Set XML encoding in the first line of XML documents:

<?xml version="1.0" encoding="utf-8"?>

You can read the full post here.

Ajax security is very important in developing your Ajax applications and it is something that many developers overlook.

Online Presentation Applications

Tagged:  

Over at Mashable they have posted a run down of 13 Online Presentation Applications. So get your favorite Business Analyst and show them how they can use the web for their next presentation (although it may take some work as they may be lost outside of the Microsoft PowerPoint world).

Below are the first five listed in the post.

http://us.ajax13.com/en/ajaxpresents/index.jsp

AjaxPresents - Presentation software portion of the Ajax13 office suite. Works with Firefox 1.5 and higher, free, and can import & export from PowerPoint and OpenOffice.

http://www.brinkpad.com

BrinkPad.com - A Java based presentation tool that allows you to create online and then download to your system to save it.

http://www.empressr.com/

Empressr.com - A tool for creating media rich presentations online with Flash and Ajax. You can share them with the public and allow them to be voted on.

Presentation Editor

Google Documents - Google made their intentions to take on Microsoft Office fairly obvious when they finally added an online presentation tool to take on PowerPoint.

http://preezo.com/

Preezo.com - Uses an Ajax-based interface for quick editing. Allows collaboration and easy sharing with clients and colleagues.

You can see the full list by clicking here.

Some of these tools look very good although I don't think that they will replace PowerPoint quite yet.

Syndicate content