Peter's Blog

Redefining the Impossible

Mochikit, Ajax, Web 2.0, Python and all that


Been looking at Mochikit, a javascript utility library, and it's good enough to remove my cynicism about javascript.

I had to play with the AJAX stuff, the ability for javascript in a browser to send a request to a server and the server to respond with data for the javascript to poke into the existing page. The big advantage of this is that the server does not have to send back a whole page for display, so the overall effect is smoother and faster.

Mochikit makes this easier and hides some of the problems with different browsers (i.e. bugs in IE). It won't work on old broken browsers but there are enough modern browsers going for free that I don't really care.

I've put my example online here but I may remove it if it gets abused or I may rearrange things and break it. In this example you type something in the box and click the link. Whatever you type is sent to the server, processed and sent back. The browser then puts the new version at the bottom of the page. Not a big deal but it's not what it does, it's the way that it does it.

Here is the code.

First, the web page:

   1  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
   2  <html>
   3      <head>
   4          <title>Peter plays with Mochikit</title>
   5          <script type="text/javascript" src="MochiKit.js"></script>
   6          <script type="text/javascript" src="Peter.js"></script>
   7      </head>
   8      <body>
   9          <h1>
  10              Peter plays with Mochikit
  11          </h1>
  12          <form name="Enter Stuff">
  13              <label>Enter something:</label>
  14              <input id="blah" name="user" value="fred"/>
  15          </form>
  16          <a href="javascript:void(0)" onclick="onDoit()">Click Me</a>
  17          <div id="putithere"/>
  18      </body>

Then the javascript (Peter.js):

   1  
   2  var gotMetadata = function (oData) {
   3      var payload = evalJSONRequest( oData);
   4      replaceChildNodes( "putithere", P( null, payload.what));
   5  };
   6  
   7  var metadataFetchFailed = function (err) {
   8    alert( "The metadata for MochiKit.Async could not be fetched");
   9  };
  10  
  11  function onDoit() {
  12      var xmlHttpReq = getXMLHttpRequest()
  13  
  14      xmlHttpReq.open( "POST", "Peter.py", true);
  15      xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  16      var d = sendXMLHttpRequest( xmlHttpReq, "blah=" + escape(getElement( "blah").value));
  17      d.addCallbacks(gotMetadata, metadataFetchFailed);
  18  }

Then the python cgi that runs on the server (Peter.py):

   1  #!/usr/bin/python
   2  
   3  import cgi
   4  
   5  form = cgi.FieldStorage()
   6  strBlah = form.getfirst( "blah", "")
   7  
   8  print """
   9  { "what": "It says %s" }
  10  """ % strBlah.replace( '"', '\\"')

This also requires the packed Mochikit library which is available in the Mochikit distribution (/packed/Mochikit/Mochikit.js). All the files can go in the same directory on the server. Obviously you have to get cgi working with python.

My main motivation for using this is to see if I can optimise the preview facility in this blog: I would like more-or-less instant preview generation. This is definitely achievable, the only problem being getting mochikit to work with php rather than python, thats where I am in unknown territory. I might cheat and use xml-rpc from python to drupal.

The only downside of Mochikit that I can see if that it is a 96k download which makes dial-up users suffer even more. You have my sympathy.


Filed under: drupal mochikit python

UTF8 Says:

over 3 years ago

When I parse utf8 characters it returns the codes, not the chars. somwhere in the line page-server-page the utf8 data is lost or not converted properly.

Other then that, this looks promising!

Peter Says:

over 3 years ago

I hadn't got as far as unicode. My main concern was editing blog posts in english. I did make sure that " characters wouldn't break the JSON formatting.

I always find unicode a pain in python, now there's javascript and XML to break as well sad

The problem is in sending the data back: I need to figure out how I'm supposed to generate the json unicode escapes. The json_py library does not look promising for this and the python unicode documentation is not helpful.

Here is a hack replacement for Peter.py that does a brute-force json unicode encoding:

   1  #!/usr/bin/python
   2  
   3  import cgi
   4  import re
   5  
   6  form = cgi.FieldStorage()
   7  strBlah = form.getfirst( "blah", "")
   8  
   9  strBlah = strBlah.replace( '\\', '\\\\').replace( '"', '\\"')
  10  
  11  #
  12  # Go through string escaping potentially unicode chars.
  13  # Minimise concatenations for speed.
  14  #
  15  nStart = 0
  16  strOut = ''
  17  
  18  for i in range(len(strBlah)):
  19      c = ord(strBlah[i])
  20      if c < 32 or c > 127:
  21          strOut += strBlah[nStart:i]
  22          strOut += '\\u%04x' % c
  23          nStart = i + 1
  24  
  25  strOut += strBlah[nStart:len(strBlah)]
  26  
  27  print """
  28  { "what": "It says %s" }
  29  """ % strOut

It now works with £ characters.

Peter

Bob Ippolito Says:

over 3 years ago

It's possible to pack a "custom profile" of MochiKit for your needs if you have a Java interpreter installed:

% scripts/pack.py Base Async |wc -c

27921

% scripts/pack.py Base Async | gzip | wc -c

7025

You do need to make sure you specify all of the components in the right order, though.

Peter Says:

over 3 years ago

Thanks for this Bob, I suspected there may be a way to do this but I couldn't find any reference to it in the documentation. The api itself is very nicely documented.

And thanks for Mochikit, it has got me interested in Javascript for more than eye candy.

Peter

Bob Ippolito Says:

over 3 years ago

Yeah, the public API is documented. The build tools aren't public API ;)

I might make it public when it's smart enough to at least determine what the correct order is, but I haven't had that many requests to make MochiKit smaller so far.

I did do some refactoring today and took off a few kb, though.

startoy Says:

about 1 year ago

I have found another site with information about this script. You can find it scripts.ajaxflakes.com

Quite good. Take a shot from this url. All in one web address.

Have Your Say

I welcome constructive comments or questions but I reserve the right to delete any comments that displease me.

Who are you?

(Optional) If you enter an email address here I might email you back. Your email address will not be sold to spammers or shown anywhere

What do you have to say?