Author Archives: fbloggs

Check out my jQuery beginners Article at

The article Dive Into jQuery (Part 1 appears in the April online and print editions of The target audience is primarily IBM i developers, but it’s actually a good introduction for anyone, regardless of server-side technology, who wants to learn jQuery.

Using Laravel: How To Use Routes, Controllers and Filters For Public and Private sections of a CMS site

If you are reading this you probably already know what Laravel is, but just in case: it’s a PHP framework for building applications. It has all the typical stuff such as MVC, DAO, ORM, a templating engine (also supports Twig from Symfony), routes, controllers, clean URLs, RESTful support etc. I really like it because it’s very clean and compact to code in. It’s also much simpler to get started with than something like Zend Frameworks 2, for example, as it doesn’t require a complex install process or configuration. In fact it pretty much just runs out of the box.

Other Tutorials on Laravel

There are a few (very few) tutorials on Laravel. If you prefer learning by watching videos I can highly recommend this series by Andrew Perkins. One text-based tutorial I’ve been working through is Dayle Rees’s. One weakness of his articles is that he starts out showing you how bits hang together, but by the time you get to filters he loses the plot and stops giving you a step-by-step working example- he teaches you concepts but doesn’t show them all working together. This is the case with his discussion about securing an admin section of your site, for example. Another tutorial, written by Nikko Bautista, covers some of the same ideas. That one also leaves some gaps. So here’s my attempt to provide a full working example, along with an explanation of how all the bits and pieces relate to one another.
Continue reading

Instructions for using a RAVIOLCASA 12

This post is for a different kind of technology – a ravioli template for making raviolis from fresh pasta. I have a hand-crank pasta machine that I use occasionally for making homemade pasta- usually fettucini. This weekend I purchased a new gadget for making ravioli – the RAVIOLCASA 12, made by Risoli. It’s an aluminum tray with dimples and serrated edges that you lay your sheets of pasta on, to form 12 raviolis at a time. It looks like this:


RAVIOLCASA 12 Ravioli Maker

It’s made in Italy. Unfortunately, the only instructions are printed on the box, in Italian. Here they are:

preparare la sfoglia, non troppo sottile, con farina e uova.
Infarinare bene la sfoglia da una sola parte
Distendere la sfoglia sul RAVIOLCASA 12 in modo da coprirlo interamente.
Mettere il ripieno negli incavi
Ricoprire con un’altra sfoglia leggermente umida
Comprimere bene con il palmo della mano e spianere il tutto
Passare accuratamente il mattarello nelle diverse direzioni esercitando una leggera pressione
Capovolgere il RAVIOLCASA 12 sul tavolo e si otterranno i ravioli tutti uguali e perfettamente chiusi.

I decided to type them in to Google Translate. Here’s the result:

preparing the dough, not too thin, with flour and eggs.
Flour the dough well on one side
Unfold the pastry on RAVIOLCASA 12 to cover it completely.
Put the filling into the recesses
Cover with another sheet slightly moist
Compress well with the palm of your hand and flatten the whole
Proceed carefully rolling pin in different directions by pressing lightly
Turn the RAVIOLCASA 12 on the table and get the ravioli are all equal and closed.

So, thanks to Google translate, I can now use my new gadget correctly! I found it funny that the box had ‘Made In Italy’ printed on it (in English, obviously), but the instructions were only in Italian (and only printed on the box! )

How To Write an SQL Trigger for IBM i

In Product Development at our company we are considering a new approach to writing transactions functions (used for shopping cart applications, etc.) which suggests a use for database triggers.  We want to update the transaction header with the current timestamp whenever the transaction detail file is updated. I decided to try using an SQL trigger to do this.

There are essentially two types of i/OS triggers: External (a program – RPG, Java, C) and SQL (written in SQL).   You can read more about them at Stored Procedures, Triggers, and User-Defined Functions on DB2 Universal Database for iSeries. I chose to write an SQL trigger because it’s really simple to do and the Redbook suggests you probably get better performance than with an external trigger. Actually – I had to write 3 triggers – one each for INSERT, DELETE and UPDATE.

In my example code, table TRIGGERA is my transaction detail file. Whenever an update happens to it, I want to update the Change date in TRIGGERB. The change date field is called CHGDATE and is a TIMESTAMP SQL data type.

To write the trigger I started editing a new source member in SEU. You can use whatever source file you like. I used library FBLOGGS, source file QSQLSRC. Here’s the code:

-- Trigger example - when updating rows in a table       
-- Drop the existing trigger, if found                   
DROP TRIGGER FBLOGGS/SQLTRIGU;                            
-- Create the trigger over table TRIGGERA:               
 CREATE TRIGGER FBLOGGS/SQLTRIGU                          
  AFTER UPDATE  ON FBLOGGS/TRIGGERA                       
  REFERENCING NEW AS NEWROW                              
  FOR EACH ROW  MODE DB2ROW                              

Brief Explanation

  • CREATE TRIGGER – creates a program object named FBLOGGS/SQLTRIGU attached to the table.
  • AFTER UPDATE – means any code in the trigger happens after (not before) an update to the table in question
  • ON FBLOGGS/TRIGGERA – name of the table that will have the trigger attached to it. So, any time an update happens to any row in TRIGGERA, this trigger will run.
  • FOR EACH ROW – the other option is FOR EACH STATEMENT, which means the trigger happens on any SQL statement touching the table (like ALTER, for example). FOR EACH ROW means the trigger happens on any affected row only.
  • REFERENCING NEW AS NEWROW – this lets you refer to the ‘after image’ of variables in an affected row. The other option is REFERENCING OLD AS OLDROW (note: NEWROW and OLDROW are arbitrary names. Call them what you want). For example, if you change ITEMPRICE in a row, you could reference the new value with: NEWROW.ITEMPRICE. In this case, I want to match the sessionid column in table TRIGGERA to the corresponding session id in TRIGGERB, the session header file.
  • FOR EACH ROW MODE DB2ROW – means for each affected row (not every row in the table- only those affected by the UPDATE operation). MODE DB2ROW means perform the trigger once per affected row. The other option is MODE DB2SQL which activates the trigger after all database updates are complete. DB2ROW is more efficient.
    WHERE A.SESSIONID = NEWROW.SESSIONID; – this is the cool part. You can use almost any valid SQL you like in your trigger (with some logical limitations). You can have more than one line of code in here too. The ; marks the end of a complete line. The Redbook has more examples. In this case, I’m updating the row in the session header table TRIGGERB that matches the session id of the affected row in TRIGGERA. The UPDATE statement assigns the current date and time to my column CHGDATE (recall I defined this as a TIMESTAMP field).
  • To compile the trigger you run this command from a standard command line:


    The first time you run it you will need to comment out the DROP TRIGGER statement in the source. But subsequent times you need it uncommented so it deletes the trigger prior to recreating it. Or you can use
    STRSQL and type the DROP TRIGGER statement on the fly.

    I repeated essentially the same code for the INSERT and DELETE triggers on TRIGGERA, the only difference being that for the DELETE trigger I used REFERENCING OLD AS OLDROW because there is no NEW.

    That’s it!

Tip for getting Gmail email attachments into Google Docs with Chrome

If you use Gmail and Chrome as your browser you can take advantage of Chrome’s clever file upload functionality to include Gmail attachments in Google docs. Chrome has drag and drop functionality that lets you drag a file from anywhere on your computer to attach it to an email. When you compose an email in the Gmail interface in Chrome just drag to file to attach onto the area just below the ‘To:’ input field to attach it to the email.

But what if you want to include an attachment in a received email in your Google docs repository? Simple! Just open the email in Gmail and download the attachment. It will appear in the bottom of your browser in a box with its name and type. From there, click the Documents link at the top of the page to go to the Google Docs list. Click ‘upload file’ and drag the file from the box in the bottom of the browser to the upload area. Done!

New Version of jQuery UI Feedback plugin

The jQuery UI Feedback plugin I wrote lets you show an informational or error message next to a UI component on your page. Its primary intended use is for AJAX-driven applications, where you want to provide some instant feedback to a user. You can read documentation, download it and try it out at this page on this blog.

I just updated it to provide a common class for each feedback message, named “ui-feedback”. This gives you the ability to turn off existing feedback messages by using this selector:


You might want to do this if multiple feedback messages potentially overlap one another.

Let me know if you find this plugin useful!

How to access cross-domain data with AJAX using JSONP, jQuery and PHP

I’m guessing that if you are reading this post you have already encountered the problem of the same origin policy with regards to retrieving data with AJAX from urls in other domains than your’s (the requesting domain). This policy, enforced by browsers, means you cannot fetch raw data from other domains with straight AJAX calls.

The Problem I Was Trying To Solve (skip this paragraph if you just want the solution)
Here’s the situation I ran into. At work, we have a timesheet entry program running on one subdomain, and Flyspray (bug-tracking software) on another subdomain. We wanted to get task descriptions from Flyspray integrated in our employee timesheet notes. Basically, the employee types a Flyspray task # for a given task they are working on, anywhere in their timesheet log entries. A jQuery script then converts that task # into a link to the task. In addition, that same script lets the user just hover over the task # to see a summary description of the task. When they hover, jQuery fires an AJAX request to a PHP script on the Flyspray subdomain. I couldn’t get it to work, so after researching it on jQuery sites I discovered my need for JSONP.

JSONP Circumvents the Same Origin Policy
Data returned from an AJAX call in JSONP (JSON with padding) format is designed to solve this problem. In jQuery, you can specify that you want either JSONP or JSON data returned from your AJAX calls. The differences between the expected returned formats of JSONP and JSON data are as follows:

  • JSON returns a JSON-formatted object only. For example: { "id" : "mydomelementid", "message": "This data came from a server!"} . This is a JSON object with 2 properties, id and message, and their corresponding values. See to find out more about JSON.
  • JSONP returns a JSON-formatted object wrapped inside a function call. For example: jsonp123( { "id" : "mydomelementid", "message": "This data came from a server!"}); .

JSONP works by injecting what looks like a local function call directly into your script, attaching it to a script tag (in the form of a url). Wikipedia has a great explanation of this.

jQuery makes it easy to do AJAX calls implementing JSONP. You can use the simple getJSON method, or the ajax method. I’ll show you examples using both. First, though, let’s look at some example PHP code, so you know how to code the server side stuff. This part is what was not clear to me when I started researching JSONP.

The Server-Side Code (PHP)
In our example, we want to return a JSON object with a property of “message” that contains some feedback text to show the user when they click a button.

header("content-type: application/json"); 

// Create a generic object.
// Assign it the properties of id (optional - id of target HTML element, from URL) 
// and 'message' - the feedback message we want the user to see. 
if (isset($_GET['id'])) $rtnjsonobj->id = $_GET['id']; 
$rtnjsonobj->message = "You got an AJAX response via JSONP from another site!";

// Wrap and write a JSON-formatted object with a function call, using the supplied value of parm 'callback' in the URL: 
echo $_GET['callback']. '('. json_encode($rtnjsonobj) . ')';    


This script returns a string in JSON-formatted object notation, wrapped in a function call. The name of the function comes from the URL parameter ‘callback’. The JSON object has one expected property (“message”) and one optional one, “id”. You provide the “id” parameter value on the URL string, also. I’ll explain its use in the second jQuery example. So, let’s say we call our script jsonp.php. The url to call it could look like this: "". What json.php writes back to the server will be: json123({"message": "You got an AJAX response via JSONP from another site!"}); . If this were a JSON call instead, we’d omit – json123(); – the function call wrapper.

(Note our PHP script creates an object on the fly, without declaring a class and instantiating one. Our object is an instance of the stdClass class, a generic PHP object. Just assigning a property to it: $rtnjsonobj->;message = "You got an AJAX response via JSONP from another site!"; achieves this. The json_encode function then converts the PHP object to a JSON-formatted string. )

The Client-Side Code (jQuery)
I’ll show you 2 examples using jQuery AJAX functions to get the message produced by jsonp.php. The first example uses the typical jQuery anonymous callback function programming pattern. The second uses a named callback function.

Example 1

$(document).ready(function() {
 $("#jsonpbtn").click(function() {
	var surl =  ""; 
	var me = $(this); 
	$.getJSON(surl,  function(rtndata) {, {duration: 4000, above: true});

This example is the simplest implementation of JSONP with jQuery. It calls our PHP script jsonp.php, passing a single parameter on the URL – callback=?. This specific syntax is the key to this being considered a JSONP AJAX call, rather than a JSON call. Note that the method is still getJSON- not getJSONP. The callback=? convention tells jQuery to generate a random function name and pass that as the value of the parameter named callback. Recall that our PHP script gets this function name with $_GET[‘callback’] , so we don’t have to worry about the actual generated name. Then, the anonymous function call (the second option on the getJSON method) does the work. In this case, it references the jQuery object that was clicked (the variable me) and calls my feedback plugin to display the message text. The fragment rtndata.message means ‘get the message property of the object rtndata (the JSON object returned by our PHP script). Feedback simply displays the message above the clicked button, for 4 seconds.

Example 2
This example uses a named callback function. Note that this capability is only supported in jQuery 1.4, so make sure you have the latest and greatest installed. As of this post, I’m using 1.4.2. I’m not sure why you would want to use a named callback function, other than to conform to DRY. The jQuery docs mention obliquely that you might want to cache your AJAX responses, but they give no explanation of how or why. Anyway, I thought it was worth trying, so here it is:

$(document).ready(function() {
$("#jsonpbtn2").click(function() {
	var surl =  ""; 
	var id = $(this).attr("id"); 
		url: surl, 
		data: {id: id},
		dataType: "jsonp",
		jsonp : "callback",
		jsonpCallback: "jsonpcallback"

// Named callback function from the ajax call when jsonpbtn2 clicked
function jsonpcallback(rtndata) { 

	// Get the id from the returned JSON string and use it to reference the target jQuery object.
	var myid = "#"; 
	$(myid).feedback(rtndata.message, {duration: 4000, above: true});

In this case, we can’t use the shorthand getJSON method, because it doesn’t have enough options. Instead, we must use the longer form ajax method. No big deal.
Here’s what’s going on. First, note the URL does not contain the callback=? parameter. Instead, we use the options jsonp and jsonpCallback, which is like writing: "jsonp.php?callback=jsonpcallback" for our url. Next, we pass the id of the DOM element (button) we clicked, as another parameter on the URL. Recall that our PHP script looks for this, and if it finds it, sends it back as a property of the returned JSON object. Next, we specify the expected data type returned from our server-side script (JSONP).

The cycle of code execution for this example is:

  • User clicks button with id of jsonbtn2
  • The browser invokes the $.ajax() method
  • The AJAX call invokes the server-side script, jsonp.php
  • jsonp.php gets the button’s id from the url parameter, constructs a JSON object with id and message properties and writes it back to the browser
  • The browser responds by running function jsonpcallback. It expects one parameter- our returned JSON object.
  • jsonpcallback retrieves the clicked button’s id from the returned JSON object, constructs a valid jQuery selector with it, and calls the feedback plugin to display the message above the button, just like in the simpler anonymous function example.

You should now understand why we pass the id back and forth. We need it in order to keep track of which element we are acting upon. We didn’t need to do this in the first example because of the magic of closures, another big topic.

That’s it!

See The Examples At Work
I’ve posted this page to show you working examples. You can view source if you want to see the jQuery code. It should be identical to what I’ve posted.

Considerations When Using JSONP
JSONP relies on injecting a script tag into your page. A side effect of this is that if you have errors in the data returned by your server, you won’t see any errors- the script tag just fails silently. An example of an error might be an incorrect callback function name (only likely in scenarios using Example 2 coding pattern), or malformed JSON.

When I first tried coding this, I got a Firebug error of ‘Invalid Label’. This totally uninformative error is the result of not wrapping the JSON object in a function call. In other words, if you have existing server code that writes JSON objects, it won’t just magically work with JSONP. Your server code must wrap a function call around the object, as I’ve shown.

Because JSONP relies on the script tag, it doesn’t use the callback features of the underlying HTTPRequest object. This means the success, failure, complete callback functions on the $.ajax() method are irrelevant and nonfunctional when you use JSONP.

How To Assign The Current Date and Time to a MySQL Datetime Field using PHP

This is a no-brainer, but I always forget how to do it. MySQL datetime fields are stored in this format: 2010-02-18 10:33:18. Here’s a trivial example showing you how to populate a datetime field with the current date in the correct format, then write it to a table:

 // Assign current date to a MySQL date field:
 $eventdate = date('Y-m-d H:i:s');
 //... (mysql connection code goes here)
 mysql_query("INSERT INTO Events (Event, EventDate) VALUES ($eventtext, $eventdate)");

Another question might be: “Why?” – when MySQL has the now() function. I needed to do this in Drupal, because I’m using the drupal_write_record function to update a table in a custom module. This requires assigning PHP values to fields in my table, rather than using any built-in MySQL functions.

The jQuery UI CSS Framework – Part 2: How To Create Widget-style Boxes

This is the second post in a series on the jQuery UI CSS Framework.    Here’s the first one.

Today I’ll show you how to create a nice looking box that has sort of a widget appearance to it. The jQuery UI components already provide similar functionality. For example, the Dialog Box is quite pretty, and you can easily make it modal or not.  But frequently we want to make a box for content somewhere on a page- much like the sorts of boxes that appear on WordPress blogs, Drupal sites or iGoogle, for example.  The jQuery UI CSS Framework comes with selectors that make this easy. Also, remember that one of the benefits of the UI framework is that you can easily change the theme of your site, without having to touch any markup or CSS – you simply change the path of the external theme css file to point to another directory. Again, the examples I’ve made use the Redmond theme.  Here’s the markup for a simple box with a nice heading:

<div id="mybox" class="ui-widget ui-widget-content ui-corner-all" style="margin-top:20px; width:300px; height: 150px;">
  <h3 class="ui-widget-header">Weather Widget</h3>
  <p><span class="ui-icon ui-icon-comment" style="margin: 0 2px 0 2px; float:left;"></span> Tomorrow it will be light during the day, and dark at night.</p>

It’s rendered (in FireFox) like this:


As you can see, the markup is pretty simple.  I’ve given the container  div an arbirtrary width and height. You might want to specify  a width, but omit the height s that the div just stretches with your content.  Let’s look at the classes used for the div, the heading (h3) and the image respectively:

The div tag:    The class  .ui-widget  ensures we use  a consistent font family and size for the content inside it. It also applies the 1.1em rule. Combined with the css selector :    body {font-size: 62.5%} this initially yields a font size of 11px at typical screen resolutions. This whole 1.1em thing can be a bit of a problem, as I’ve discussed in other posts. For example, if I embed another container using the same selectors, my text comes out at 12.1px (1.1x 1.1em).  You can inspect your element with Chris Pederick’s Web Developer plugin for FireFox to see bad behavior at work. For example, see below:

Font size for second container text is now 12.1px, not 11px.

Font size for second container text is now 12.1px, not 11px.

I ran into this in an app where I had tabs embedded inside tabs. The jQuery UI code applies the .ui-widget class to tabbed content containers behind the scenes, so I ended up with oversized text compared to the rest of my page.

The class of .ui-widget-content applies the border, along with some padding. the .ui-corner-all selector gives us rounded corners (in FireFox and Chrome, not IE).

The h3 tag: This uses the class  .ui-widget-header. This is pretty self explanatory. It applies a nice background on white text (based on the Redmond theme) to our heading. You can use this class on other tags, too. For example, I use it on tr tags for my table heading rows.

The image (span) tag: (.ui-icon and .ui-icon-comment).  I just threw this in as a bonus for this lesson. jQuery UI is very clever at handling icons. Instead of having a whole bunch of images, you basically have one big image sliced into squares, with each icon class being a small window over the appropriate square. This is a variation on the famous Sliding Doors sprite concept at A List Apart.  It saves different image resources having to be loaded, to optimize performance. It also allows the icons to be themed easily, because you don’t have to change the path for an image, as you would for a typical HTML img tag. You can also apply a hover state to any icon in the set, simply by setting the class to .ui-state-highlight.  We’ll cover this in more detail in a later article.

In this case, I used a span tag to display the comment icon. This could also be an anchor tag, or a li tag, or whatever.   The .ui-icon class gives us a 16 x 16 pixel area blocked out for whatever icon we choose. The .ui-icon-comment class displays a comment icon (similarly, .ui-icon-trash shows a trash can, etc. etc.). You can see the entire set of available icons at the Themeroller page.  The default setting for .ui-icon is display:block, which forces a line break, which is why I had to add an inline style setting of “float: left” to get it to appear on the same line as my text.

That’s it!  the next article will show you how to style pretty forms elements with the framework.

How To Embed A Google Calendar Gadget In Your Web Site

Google provides two simple ways, other than you writing your own client code to talk to their APIs, to embed a calendar in your web page. One method is easily found by Googling for the info. This link explains how you can generate a piece of code directly from your calendar settings page, which you then paste into your page. This code uses a simple iframe. The other method is to use a Google Gadget. While they are primarily meant to embed in iGoogle, you can also embed them in your own site. Here’s how:

  1. Log in to the Google account that owns the calendar you want to embed.
  2. Make sure the sharing option is set to public (if that’s truly what you want!)
  3. Go to this URL: This is a Google gadget.  Note the last part of the URL – calendar3.xml .  DO NOT use calendar.xml . It doesn’t work any more (as I found out to my chagrin when the  calendar for our local soccer club web site suddenly stopped rendering for no apparent reason).
  4. You’ll see a link in the bottom right hand side of the page, titled: Embed this gadget >> , which means ‘Embed this gadget in some page other than at iGoogle’.   Click on this link .
  5. Customize the gadget’s appearance with the available options. You should see the changes you make reflected immediately. If not, click ‘Preview Changes’.
  6. Once you are happy with the final appearance, click ‘Get the code’
  7. Select the generated code in the text box, copy and paste it into your page.

The gadget uses an XML feed via web services to draw the content directly in the page, as opposed to using an Iframe, which for a Geek like me is a much more elegant solution than more easily found one. Plus, I like the fact you get a monthly calendar with a list of upcoming events directly below it. (When you customize the gadget’s appearance, change the height to 400px, for example, and you’llsee what I mean).

You can see a working example at Saanich Peninsula Soccer Club’s site.