Categories
Dev

Simple JSON-RPC Class

JSON-RPC is a simple methode to transfer data without site refreshing from the server to the client. It’s an alternative to AJAX calls and used in many web applications, for example most of the google apps use it for their client-server communication. Here’s my simple implementation:

The Class

jsonRPC = function() {
   cbstore = new Object();
   var counter = 0;
   var base = "insert your base url here";
   var encode = encodeURIComponent;

   var cleanup = function(id, s) {
      delete this.cbstore[id];
      setTimeout(function() {
         document.body.removeChild(s);
      }, 0);
   }
   this.send = function(params, callback) {
      var id = "cb" + ++counter;
      var timeout = setTimeout(function() {
         cleanup(id, s);
         callback(null);
      }, 2000);
      cbstore[id] = function(data) {
         //cancelTimeout(timeout);
         cleanup(id, s);
         callback(data);
      };
      var s = document.createElement("script");
      document.body.appendChild(s);
      s.src = base + "?callback=cbstore." + id +
      "&" + (params);
   }
   this.call = function(params, callback) {
      this.send(params, function(data) {
         if (!data || data.Status.code != "200") {
            callback(null);
         } else {
            var c = data.pois;
            callback(c);
         }
      });
   }
}

The Serverside

To trigger the clientside callback function you must insert it in your server-side response. The response must look like this:

print (insert the callback function process from GET here + "({Status: { code: 200, request: \"getpois\" }, pois: [");


//output of your data in JSON format

print("]})");

Usage

mycall = new jsonRPC();
mycall.call("insert some params here", function(json) {
	if (!json || json == undefined || json == null)
		return;

       //do something with the response data here



});

What’s next

To be honest, this is a very ugly implmentation and I have to work over it quite soon. It’s now not possible to use the class for different requests. So I will add a constructor in a next version, allowing to pass a the base url when instancing the object. Also the response data object (pois) is not changeable via constructor variable -> need to be changed. (FYI: I used this class to load objects onto a visual map, therefore the name pointofinterst.) For now you can play with that code a litte bit an evaluate how it works for you as an AJAX alternative.

Categories
Thinktank

Oldschool

dc10_12.JPG

Da werden Erinnerungen wach: an eine Doppelstunde Informatik in der man mit Sage und Schreib mit 1 – 2K/s (1 ISDN Anschluss für ca. 15 Computer!) 2 MP3’s saugen konnte um sie dann in einer Box voll mit Floppys nach Hause beförderte. Und man hat sich trotzdem gefreut!

Categories
Life

My Boarding Skills