Greg DeKoenigsberg Speaks

Greg meets Ajax, chapter 1

Posted in Uncategorized by Greg DeKoenigsberg on April 29, 2010

I hear this AJAX thing is really cool. I’ve decided that I need to learn how it works, exactly. So I’m putting myself through AJAX school. I am going to share this learning process with you, my friends, for a few reasons:

1. When I’m learning something, I find that writing it all down helps me think through things more effectively.

2. If I share what I’ve written, maybe someone else will find it useful.

3. If I share what I’ve written, maybe someone else will show me a better way.

So here’s what I know about AJAX, right now, today: it allows you to change a web page without reloading that web page.

That’s about it. The sum extent of my AJAX knowledge.

When you change data on your local web client using Javascript, how do you transmit that data back to the server? I don’t quite know.

When something changes on your server, how exactly do you pull those changes without reloading the web page? I don’t quite know.

Time to start figuring it out.

* * *

There’s a really cool jQuery application out there for sticky notes. Want to cover a web page with sticky notes? I do, and it’s awesome! Try it out. Also, if you’re following along, go get the client code. Just drop it into a directory on your laptop or wherever, and use the “File: Open” in your browser of choice, and it will “just work”. Play with it! Make some sticky notes. Drag them around the screen. Knock yourself out. (And then send your thanks to Daniel Nowak for being such a cool guy.)

Trouble is, when you reload that web page, all the cool sticky notes you created go away. Poof. Because, see, it’s all just data in your local browser.

I want to figure out a way to make those sticky notes persist. I want a board full of sticky notes posted by all of my friends. Which means that we’re going to have to store that data somewhere that’s not inside of my web browser. :)

Let’s start with the Sticky Note code. Which is all client-side. That’s the cool thing about modern Javascript; you can now have an entire application running completely in your browser.

The stickynotes code looks pretty straightforward. There’s the script itself, script/jquery.stickynotes.js, and there’s the HTML page, which loads up the script, feeds it some initial data — in this case, a default stickynote — and runs it. I don’t understand the guts quite yet, but I can look at the data structure and see that it is dead simple: an array of notes, each of which has text, pos_x, pos_y, width, and height attributes.

The demo running online and the version of the code I’ve downloaded are subtly different. Fortunately, the downloaded version has this great for developers: whenever I change the state of any of the stickynotes on my board, it sends a Javascript alert with the new settings of that note. Which is awesome!

Now I have my first simpleminded goal: every time I get one of those nice Javascript alerts, I want to send that data to some web server instead. I’m sure that “Ajax” is the right way — but what does that mean, exactly?

* * *

I start like any simpleton would: I google “Ajax”.

Seriously.

I read the Wikipedia page on Ajax. At the bottom, there’s a link to “jQuery” — oh, yeah, maybe the functionality I’m looking for is built into jQuery, duh. So now I read the jQuery wikipedia entry — and the function call for what I’m trying to do is right there on the wikipedia page! To wit:

It is possible to perform browser-independent Ajax queries using $.ajax and associated methods to load and manipulate remote data.

$.ajax({
  type: "POST",
  url: "some.php",
  data: "name=John&location=Boston",
  success: function(msg){
    alert( "Data Saved: " + msg );
  }
});

This example posts the data name=John and location=Boston to some.php on the server. When this request finishes successfully, the success function is called to alert the user.

Hm! All right, so instead of “name=John&location=Boston”, my POST will probably look something like “action=created&id=1&text=some_url_encoded_text&pos_x=100&pos+y=100″. I can do that — but first, I need to put together a script on some web server somewhere that can do something with this data.

Enter PHP. My web skills are admittedly out-of-date; the last time I wrote web code that anyone actually counted on to work was some 15 years ago, when Perl and CGI ruled the world. Back then, I would have had to hack together a CGI script to do this. PHP now makes this much easier — although it’ll still take me a while to put together even the most basic PHP script. A quick googling of “php forms” refreshes my memory about its syntax for accepting GET and POST data, and after a bit of trial and error (and remembering the difference between GET and POST, heh) I’ve got a bit of code (php tags stripped for the benefit of our php-based blog, heh):

$id = $_GET['id'];
$text = $_GET['text'];
$pos_x = $_GET['pos_x'];
$pos_y = $_GET['pos_y'];

$myFile = "testFile.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
$string = $id . "|" . $text . "|" . $pos_x . "|" . $pos_y . "\n";
fwrite($fh, $string);
fclose($fh);

echo "$id written";

(Yes, yes, I know: this is hopelessly insecure. Nothing like allowing untested form data to be written directly to your filesystem. This is, I can assure you, very temporary.)

Now it’s time to edit the stickynote code to perform this very basic function. I take the stickynote alert code:

var edited = function(note) {
                                alert("Edited note with id " + note.id + ", new text is: " + note.text);
                        }

And I add a bit of AJAX-y magic:

var edited = function(note) {
                                alert("Edited note with id " + note.id + ", new text is: " + note.text);
                                $.ajax({
                                    type: "GET",
                                    url: "http://highlysekrit.net/ajaxlistener.php",
                                    data: "action=edited&id=" + note.id + "&text=" + escape(note.text) + "&pos_x=" + note.pos_x + "&pos_y=" + note.pos_y
                                }); 
                        }

And that’s it. It works: when I edit a note in my browser, another status line is appended to the end of text file on my web server. Hurray! First simpleminded goal achieved. A little bit of Googling, a little bit of jQuery, a little bit of PHP, and a few hours of time. Sure, this would have taken a skilled practitioner about two minutes, but not a bad start to get a grasp of AJAX and knock the rust off.

Next goal: retrieving new note data from the server and rendering it in the browser. If I can get this right, I’ll be able to have multiple people sharing a sticky pad workspace — w00t! We’ll see how it goes.

Now, the *big* goal is to add a stickynote module to Etherpad, in order to further leverage Etherpad’s Powers of Amazing — but I’ve got quite a bit more to learn before I’m ready to tackle that challenge myself.

Of course, others among you may be up to that challenge right now. If so… be my guest. ;)

(p.s. if anybody knows of a simple free software tool that already does this, please let me know.)

About these ads

4 Responses

Subscribe to comments with RSS.

  1. Brian said, on April 29, 2010 at 11:34 am

    Heh, when I read the title first thing I thought of was you meeting Fedora’s ajax (aka Adam Jackson). ;-)

  2. Max said, on April 29, 2010 at 11:46 am

    In which chapter of this series will Ajax fight Hector?

  3. [...] post: Greg meets Ajax, chapter 1 « Greg DeKoenigsberg Speaks If you enjoyed this article please consider sharing [...]

  4. David Means said, on May 20, 2010 at 11:14 am

    A great start. You probably get lots of messages about how to proceed, but here’s my .02 worth:
    The communication between browser and server is fundamentally asymmetric: stuff goes to the server as a GET or POST (name=value pairs), and comes back to the browser as XML (value sequences). Looked at in this way, though, AJAX is just a reincarnation of the message-passing schemes of the 1980s for invoking remote procedures. Consequently, all of the stuff computer science professors have accumulated about procedure calling, compartmentalization of code, and other best practices can be applied to this “new” scheme.
    In fact, it is reasonably easy to write a whole application as a single browser screen, with the necessary Javascript being downloaded as needed by the various parts of the application. Probably this forum is not the right place for me to hold forth on this topic, but if you’d like to pursue this further, I would be happy to oblige.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 34 other followers

%d bloggers like this: