NodeJS Tutorial – Part 2, Routing

Posted: May 31st, 2010 | Author: Rob Searles | Filed under: JavaScript, Tutorials | Tags: | Comments
Note: This is the second part of my NodeJS tutorial. You may want to go back to the first part of this tutorial if you haven’t already read it.

In the first part of this tutorial we looked at reading a document from CouchDB and keeping our markup separate from our code using Haml templates. We arrived at the point where we clicked on a link, but nothing happened. Today we are going to put that right with some very simple routing.

The URL Module

The basis of all routing is the URL. Fortunately, Node has some basic functions which handle reading the URL so we can then decide what the user is actually trying to do.

First, we want to make sure we have included the URL module.

var sys = require('sys'),
fs = require('fs'),
http = require('http'),
url = require('url');

The next step is to extrapolate the path name from the URL that the user has visited:

Read the rest of this entry »


NodeJS Tutorial with CouchDB and Haml – ErdNodeFlips

Posted: May 28th, 2010 | Author: Rob Searles | Filed under: JavaScript, Tutorials | Tags: | Comments

The aim of this tutorial is to create a Node powered web app using a CouchDB database and Haml based templates. I wanted something relatively simple that I could do in a couple of sittings, but complex enough to be of some actual use. In the end I opted for a “top 10 list” type application. The functionality being as follows:

  1. To list a number of items
  2. To remove an item from the list
  3. To add an item to the list

Obviously, before getting cracking with this tutorial I had to think up a name for this “killer app” of the Node world.

So I give you ErdNodeFlips! In honour of erdnussflips – the strangely addictive Wotsit type things that taste of peanut butter and stick to the top of your mouth. Yum! (OMG – they even have their own Facebook page!)

All code is available on GitHub.

Read the rest of this entry »


jQuery Validate URL, adding “http://”

Posted: May 27th, 2010 | Author: Rob Searles | Filed under: JavaScript, Tutorials | Tags: | Comments

A project we have going on here at ibrow towers involves quite a bit of jQuery Validation. Whilst the Validation plugin is great with the default functions it offers, what makes it truly excellent is the fact that it is easily extendable.

For example, one thing that has been bugging me is to validate a URL the user must type in the initial http://. But why? Can the validation not just assume that if, for example, www.robsearles.com is typed in, that the user actually meant http://www.robsearles.com?

Well, after a quick read of the documentation and a hack around this little irritant is now gone. It’s all down to addMethod() which lets you add a custom validation method. Lets create one called complete_url().

jQuery.validator.addMethod("complete_url", function(val, elem) {
    // will contain our validation code
}, 'You must enter a valid URL');

A quick word about return values. If the method returns true, everything is considered OK. However, if false is returned then validation is assumed to have failed.

Our new method needs to do three things:

  1. If no url, don’t do anything
  2. Check that the user had entered http:// in their URL, if not, add it in for them.
  3. Check that the URL is now valid. For this I just used the source for the original url validation method.

Lets translate this into some code:

jQuery.validator.addMethod("complete_url", function(val, elem) {
    // if no url, don't do anything
    if (val.length == 0) { return true; }
 
    // if user has not entered http:// https:// or ftp:// assume they mean http://
    if(!/^(https?|ftp):\/\//i.test(val)) {
        val = 'http://'+val; // set both the value
        $(elem).val(val); // also update the form element
    }
    // now check if valid url
    // http://docs.jquery.com/Plugins/Validation/Methods/url
    // contributed by Scott Gonzalez: http://projects.scottsplayground.com/iri/
    return /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(val);
});

Validating the form with this new method is very straight forward:

$("#form1").validate({
    rules: {
        url: "complete_url"
    }
});

Feel free to use/copy/modify as you see fit. If you do use it, why not let me know, or drop me a trackback?

Have fun

Other jQuery Specific Posts


Hacking about with Node.JS

Posted: March 28th, 2010 | Author: Rob Searles | Filed under: JavaScript | Tags: | Comments

Update: If you are looking for a NodeJS tutorial, visit this post: NodeJS Tutorial with CouchDB and Haml.

After proclaiming that Node.JS is exciting stuff, today was the first time I’ve actually had the time to play around with it properly. I’ve been thinking about writing a custom FTP server for a project that we’re working on at the moment, and instead of starting from scratch, I thought I’d see if anyone else has tried to do the same. Fortunately I found Andrew Johnston started an FTP server only a few months ago: NodeFTPd on GitHub. I quickly created a clone and tried it out. It didn’t work! Node.JS is such a fast moving target that a lot of the API has been changed in the 3 months since Andrew initially released nodeftpd.

Perfect! This meant that I could play around with Node!

I’ve been hacking about on it for 4 hours or so, you can see my results at GitHub.

So what have my 4 hours of hacking around taught me about Node? Well, it’s not just exciting, it also bloody good fun!


IE 7 indexOf() Replacement

Posted: March 11th, 2010 | Author: Rob Searles | Filed under: JavaScript | Tags: | Comments

Everyday I hate IE a little bit more, and by the same token, everyday I love jQuery that little bit more.

The reason for my hate/love feelings today was due to a bug caused by IE 7 not supporting the indexOf() method. I have no idea why IE doesn’t support this method, but it is annoying never-the-less. However, there is an easy fix if you are using jQuery – the inArray() function.

The inArray() function is pretty simple to use.

Instead of having:

haystack_array.indexOf("needle")

You should use:

jQuery.inArray("needle", haystack_array)

For those of you crazy nutters that aren’t using jQuery, there is a good post on this blog that will help you out.


First Steps with Node.js: exciting stuff

Posted: November 29th, 2009 | Author: Rob Searles | Filed under: JavaScript, Opinion | Tags: | Comments
If you are looking for a NodeJS tutorial, visit this post: NodeJS Tutorial with CouchDB and Haml.

During my Saturday morning reading yesterday I fell over something called Node.js.  According to the website

Node’s goal is to provide an easy way to build scalable network programs.

which is kind of exciting, but not mind blowing, however, Ryan Dahl’s GitHub page describes it as

evented I/O for v8 javascript

Which is slightly more exciting. However, it is when you start to play around with it that things begin to get very exciting indeed.

Read the rest of this entry »


Fixed – jQuery DatePicker not working in Thickbox

Posted: January 27th, 2009 | Author: Rob Searles | Filed under: JavaScript | Tags: | Comments

I’ve been struggling today for about an hour trying to get jQuery’s DatePicker working in Thickbox. There appeared to be some kind of conflict. I tried hacking up the Datepicker plugin file, changing the z-index of the CSS but nothing. The date picker wasn’t even being called.

Eventually I found that other people were having the same problem, and a comment by Kevin Luck (the author of DatePicker) flicked my brain into gear.

The problem was that I was initialising the datepicker on page load, not on the loading of the thickbox content.

For example, at the start of the page the Thickbox was going to be loaded in I had this:

<script type="text/javascript">
	$(function(){
		// initiate date picker
		$('.pick-date').datePicker();
	});
</script>
</head>

However, I found that if I removed that from the head, and instead inserted it in the Thickbox content, e.g:

<div id="MyThickboxContent">
<script type="text/javascript">
	$(function(){
		// initiate date picker
		$('.pick-date').datePicker();
	});
</script>

It worked fine, problem solved!


jQuery: Link override with search box

Posted: November 26th, 2008 | Author: Rob Searles | Filed under: JavaScript | Tags: | Comments


Just been working on a little something for a client involving Google Custom Search Engines.

The app we’re building uses 4 different search engines which are all specialised in a certain area. There is a central “Overview” page that gets the top results for the search from each of the search engines, plus there are normal links above the search box that, when clicked on should take the user directly to the Custom Search Engine results page for the string in the search box.

Sounds quite straightforward, but the links also save the current search (which may be different to the search box if the user has just entered a search into the box) so in this case, the old search needs to be stripped and the new search carried forward to the Custom Search Engine.

So it’s a little more tricky, but fortunately using jQuery and the URL Parser plugin by Mark Perkins I was able to cut out most of the tricky stuff.

Below is a little demo to illustrate the main part of the jQuery usage. Before you conduct a search, you should be able to click on the links to go and search Google for those keywords (jQuery, CakePHP, Ruby On Rails and No Search conducted). If you enter a string in the box and hit the “Search” button, you’ll go to Google and search for the string. However, if you enter a string in the search box but then click on a link, you’ll be taken to Google and search for the string.

This isn’t quite how it works on the client site, but is enough to show how the jQuery is being used.

Search Google

 

Javascript code in the <head> tags is:

<script src="/javascript/jquery.1.2.6.js" type="text/javascript"></script> 
<script src="/javascript/jquery.url.js" type="text/javascript"></script>
<script type="text/javascript"><!--
$(function(){
	$("#jQuerySearchExample a").click(function () {
		var path = "http://www.google.co.uk/";
		path += jQuery.url.setUrl($(this).attr("href")).attr("path");
		path += "?"+$("#jQuerySearchExampleInput").serialize();
		$(this).attr("href", path);
	});
});
// --></script>

And the HTML is as follows:

<ul id="jQuerySearchExample">
	<li><a href="http://www.google.co.uk/search" target="_blank">No Search</a></li>
	<li><a href="http://www.google.co.uk/search?q=jquery" target="_blank">jQuery</a></li>
	<li><a href="http://www.google.co.uk/search?q=CakePHP" target="_blank">CakePHP</a></li>
	<li><a href="http://www.google.co.uk/search?q=ruby+on+rails" target="_blank">Ruby On Rail</a></li>
</ul>
Search Google
<form action="http://www.google.com/search" method="get"> 
<input id="jQuerySearchExampleInput" name="q" type="text" /> 
<input type="submit" value="Search" />
</form>

As you can see, I use

jQuery.url.setUrl($(this).attr("href")).attr("path");

To strip out the current query string from the hard coded URL and then

"?"+$("#jQuerySearchExampleInput").serialize();

To replace it with the string within the search box.

Took a bit of faffing about, but works quite well