A WebSocket Mojolicious/DBI Example
Building on my (second) example from my recent post A Simple Mojolicious/DBI Example, I thought I would take it just a little bit futher. One of my favorite features of Mojolicious is that it comes with WebSockets out of the box! In this example I show how you can take the example script and allow it to run without refreshing the window.
WebSockets, part of the new HTML5 standard, provide a two way means of communication between the client and server. While there have been hackish means of accomplishing this task for years (AJAX), WebSockets make these connections very simple. Of course the style changes from a procedural (“render this content”, “POST new data”, etc) to event driven (“on click”, “on message”, etc)
In this version of the example, notice that the
/insert route has been declared as a websocket. This new route defines an
on message handler for what to do when the server receives a websocket message. First it decodes the JSON data, inserts it into the database, then it generates a new HTML row for the client and sends it back to the client via that same websocket connection.
insert which opens a websocket and defines an
onopen handler for sending the data, and an
onmessage handler which receives the new HTML row and inserts it into the displayed table. This function makes use of jQuery which I pull in from the Google CDN.
One more thing to notice is that I now have a separate template for the table rows. The index page uses this to build the initial table, but since it is separated I can use it to generate the new inserted row HTML too!
Finally one might notice the use of Mojolicious’ tag helpers in places. I especially like using the