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() {
     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"
    }
  });
});

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 pythonimport osimport wsgiref.handlersfrom google.appengine.ext import webappfrom google.appengine.ext.webapp import template# MvcHandlerclass 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'))# maindef main(): application = webapp.WSGIApplication([('/mvc/', MvcHandler)], debug=True) wsgiref.handlers.CGIHandler().run(application)if __name__ == '__main__': main()

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

  • 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!  

    The Room

    Just got home from the best Midnight Movie Mamacita show yet - "The Room". This is an absolute must see, but you have to watch it in at the cinema, no DVD's allowed! Yes the movie has appallingly bad acting, writing and cinematography, but it's the audience participation that makes it. Make sure you take a bag of plastic spoons with you so you can shout "SPOON!" and throw spoons at the screen every time you see the spoon picture in the background (guess who got there late and had to sit on the front row!); marvel at the icky lump on Lisa's throat; yell "Where's this filmed?" at every tourist shot of San Francisco; chant "Go! Go! Go!" every time they cross the Golden Gate bridge; make zen chanting like "Om" sounds along with every kiss; say hello & goodbye to Danny as he walks in and out of every shot... the list goes on. The most fun I've had in years, I'm going back for next months screening and taking everyone I can find :-)

    Happiness is a bad movie

    Media_httpblogrosscoopscomuploadedimages165797154jpg_sitpupdhyhiicwm
    As many of you know, I'm a sucker for bad movie. So it was with immense anticipation last night that I finally headed out to a meeting of the midnite movie mamacita, to check out the original 70's version of "Quel maledetto treno blindato", aka "The Inglorious Bastards". You know, the movie Tarantino has just remade with Brad Pitt? Well if its half as good as the original its gonna be great. It's an italian WW2 epic where everyone is very painfully 70's, with all the bad editing, hammy acting, giant sunglasses, even bigger mustaches, and naked fraulines with machine guns you could wish for! Heaven :-)

    The MMMamacita folks were great too, with some spectacularly bad previews of their upcoming screenings (Japanese horror movie Hausu looks like a must see), and competitions to win tickets to press screenings, movie posters, etc. Even the small audience were great, shouting out funny stuff all the way through the movie. I definitely know what I'll be doing with my fri/sat nights from now on!