Google Web Sockets

I got all excited yesterday about the inclusion of Web Sockets in Google Chrome, and even more excited today when I noticed the latest version of Google Go now has a server side implementation of Web Sockets. Naturally I had to write a quick test to check it out :-) Here's the Google Go server implementation:

package main
import ( "http"; "io"; "websocket"; )
func EchoServer(ws *websocket.Conn) {
  io.Copy(ws, ws);
}
func main() {
  http.Handle("/echo", websocket.Handler(EchoServer));
  err := http.ListenAndServe(":12345", nil);
}

And here's the client side javascript that updates the contents of a DIV named 'banner'...

if ("WebSocket" in window) {
  var ws = new WebSocket("ws://localhost:12345/echo");
  ws.onopen = function(){ws.send("My first WebSocket worked!");};
  ws.onmessage = function(evt){document.getElementById('banner').innerText=evt.data;};
  ws.onclose = function(){};
}

Filed under  //

Posted by

Comments [0]

Best OSX Dock tip ever

Easily add blank spacers to your dock by using the following in Terminal...

defaults write com.apple.dock persistent-apps -array-add '{tile-data={}; tile-type="spacer-tile";}'
killall Dock

This adds a blank space to the right side of your dock. You can then click on this blank space to drag it anywhere in the dock, or out of the dock to remove it.

Filed under  //

Posted by

Comments [0]

Using C# objects inside of your Javascript

Here's an easy way to get your C# objects transferred via AJAX & JSON so that you can use them inside of your html pages Javascript. First here's the C# WebMethod we want to call...

[WebMethod]
public static string Test()
{
var data = new {
page = 1,
totalRows = 2,
rows = new List<DummyData>() {
new DummyData { firstname = "Ross", lastname = "Cooper" },
new DummyData { firstname = "Bob", lastname = "Sagat" }
}
};
return new JavaScriptSerializer().Serialize(data);
}
And here is the javascript that uses jQuery to call Test() via AJAX and decode the returned JSON into a javascript object...

$(document).ready(function() {
$.ajax({
type: "POST",
url: "Default.aspx/Test",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
var data = eval("(" + msg.d + ")");
alert(data.rows[0].firstname); // prints "Ross"
}
});
});

Filed under  //

Posted by

Comments [0]

jQuery, AJAX and Google App Engine

Heres a quick example of how to use ajax with Google App Engine. First the code in index.html...


<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function() {
$.post("/mvc/", {name:"Ross"}, function(data){
$("#test").html(data);
});
});
</script>
<div id="test">loading...</div>
</body>
</html>

And here's the main.py. The get method returns the initial page and the post method handles the ajax callback...


#!/usr/bin/env python
import os
import wsgiref.handlers
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template

# MvcHandler
class MvcHandler(webapp.RequestHandler):
def get(self):
path = os.path.join(os.path.dirname(__file__), 'templates/index.html')
self.response.out.write(template.render(path, {}))

def post(self):
self.response.out.write("Hello "+self.request.get('name'))

# main
def main():
application = webapp.WSGIApplication([('/mvc/', MvcHandler)], debug=True)
wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
main()

Filed under  //

Posted by

Comments [0]

Easy PHP MVC like Controllers!

Recently I was trying out jQuery's AJAX wrapper, and wanted a way of calling multiple functions on a single PHP class in an MVC like way. This is the shortest simplest code I could come up with. Note this was just a test, so it's not production proof, but feel free to take it and expand upon it...

First heres my **index.html**, using jQuery to populate 2 <li> tags...

<head>

 <script type="text/javascript" src="scripts/jquery-1.3.2.js"></script>

</head>

<body>

 <script type="text/javascript">

  $(document).ready(function(){

   $("#userAgent").load("mvc.php?co=Test&ac=UserAgent");

   $("#hello").load("mvc.php?co=Test&ac=Hello&id=RossCoops");

  });

 </script>

 <ul>

  <li id="userAgent"></li>

  <li id="hello"></li>

 </ul>

</body>

 

And here's my controllers/TestController.php...

 

class TestController

{

 function UserAgent() {

  echo $_SERVER['HTTP_USER_AGENT'];

 }

 function Hello() {

  echo "Hello ".$_GET["id"];

 }

}

 

And here's the mvc.php code that ties it all together. First it takes the co param and adds 'Controller' to it; then it looks for a php file with that name in the controllers directory; then it creates an instance of that class and calls a method on it as named in the ac param...

 

$type = $_GET["co"]."Controller";

require_once("controllers/".$type.".php");

$controller = new $type;

$controller->$_GET["ac"]();

 

Short & sweet huh? Of course, the main drawback here is that all the controller methods cannot take params, but could get around this by using $_GET to pull params from the HttpRequest just like I get the id param in TestController.Hello(). You could go even further by using reflection to inspect a method's params, and then pre-populate them before invoking the method from **mvc.php**... but that's an exercise for another day!

 

Filed under  //

Posted by

Comments [0]

Prototype Enumerable

In the previous post, I iterated over an array with the following code...

var ids=new Array('1','2');
for (var i=0;i<ids.length;i++)
$(ids[i]).style.display = 'none';
You can do this in one line of code using prototype's Enumerable.each method...

['1','2'].each(function(id,index) {$(id).style.display = 'none';});

Filed under  //

Posted by

Comments [0]

Quick fading tabs with scriptaculous

I was recently working on a website project where I realized I basically had too much data to neatly show on 1 page, so I decided to add a really simple tab like area to the page, and a cool fade as we moved between tabs. Essentially each tab area is represented by a DIV tag, and a quick bit of javascript hides and shows the DIV's.

First download & add the prototype and scriptaculous libraries to your page...

<head>
 <script src="scripts/prototype.js" type="text/javascript"></script>
 <script src="scripts/scriptaculous.js?load=effects" type="text/javascript"></script>
</head>

Here's the real simple javascript code that hides all the DIV's and then shows the selected one. Note that I'm just using 2 tabs in this example...

<script>
function showId(id) {
 var ids=new Array('1','2');
 for (var i=0;i<ids.length;i++)
  $(ids[i]).style.display = 'none';
 $(id).appear();
}
</script>

The tabs themselves are just A links. When you click on one of the links, it fires the above script code...

Pages:
info
home

And finally each tab area is just a DIV too. Obviously, you would replace ... content ... with whatever content you wanted to show in each tab...

<div id="1" style="display:inline;"> ... content ... </div>
<div id="2" style="display:none;"> ... content ... </div>

And that's it! You can see the effect on some of the pages at http://iphone.rosscoops.com

Filed under  //

Posted by

Comments [0]

Open letter on encouraging innovation in HTML

Last night I climbed into bed and had a eureka moment that kept me awake for a couple of hours. Basically I think I identified how HTML & web browsers need to change to encourage further innovation on the internet. The idea was still ringing around my head this morning so I thought I'd write up the following brain dump and put it out on the web, maybe start a discussion.

It ended up being way too big to fit into a blog entry, so I have it on a separate page here. I'd be interested to hear what you think about it...

Filed under  //

Posted by

Comments [0]

80 AJAX Solutions

Great roundup of 80 AJAX techniques here.

Filed under  //

Posted by

Comments [0]

iPhone & Regex

Want to use regular expressions in your iPhone app? Check out the wonderful RegexKitLite at http://regexkit.sourceforge.net/RegexKitLite/. Basically it uses categories to extend NSString with a bunch of useful methods for performing all your favorite regular expression matches and compares.

Filed under  //

Posted by

Comments [0]