Tag Archives: JavaScript

Check out my jQuery beginners Article at iprodeveloper.com

The article Dive Into jQuery (Part 1 appears in the April online and print editions of iProDeveloper.com. 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.

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 json.org 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.

<?php
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: "http://www.example.com/jsonp.php?callback=jsonp123". 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 =  "http://www.fbloggs.com/sandbox/jsonp.php?callback=?"; 
	var me = $(this); 
	$.getJSON(surl,  function(rtndata) { 
		me.feedback(rtndata.message, {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 =  "http://www.fbloggs.com/sandbox/jsonp.php"; 
	var id = $(this).attr("id"); 
	$.ajax({
		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 = "#"+rtndata.id; 
	$(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.

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>
</div>

It’s rendered (in FireFox) like this:

weatherwidget

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.

New Version of jQuery Feedback Plugin released

This is version 1.0.1. It corrects a bug where the ‘above’ and ‘below’ options did not work, and it also lets you place a message immediately above an element, with the left side of the message area aligned with the left edge of the element itself. I have also updated the demo page to include a demo of using the ‘above’ option, and to style the buttons using the jQuery UI CSS framework.  I’ve also update the link to the zip file to download, on this page,  to point to the new version.

This plugin lets you write feedback messages anywhere on your page. I usually use it to provide some response from an AJAX call.

The jQuery UI CSS Framework – Part 1: Intro and How To Style a Button

This is the first in a series of articles on the jQuery UI CSS Framework.. This is a powerful suite of CSS selectors that you can use to build web applications with a consistent UI. The main jQuery UI demo page shows you a list of UI widgets (which are still somewhat limited in scope compared to ExtJS, for example), but it doesn’t do a very good job on selling you on the benefits of designing other UI components, or components of those widgets, using the UI CSS framework. In this article I explain the framework, its benefits and weaknesses, and show you one simple example of styling a button.

What is the jQuery UI CSS Framework?

It is a set of CSS selectors that let you design your web pages to conform to the jQuery UI widgets standards. Quote:

The jQuery UI CSS Framework provide semantic presentation classes to indicate the role of an element within a widget such as a header, content area, or clickable region. These are applied consistently across all widgets so a clickable tab, accordian or button will all have the same “ui-state-default” class applied to indicate that it is clickable.

(from the jQuery UI Theming documentation page).

Benefits of the jQuery UI CSS Framework

Here are the top benefits I think the framework has to offer:

  • It handles difficult design issues for you. For example, you can apply rounded corners to buttons and links easily, just by adding a class of  “ui-corner-all” to your element.
  • It gives you a consistent look and feel to your page design elements
  • You can use the jQuery UI widgets (such as tabs, dialog boxes, accordions, etc. in conjunction with your own custom elements (text, tables, buttons, boxes, icons, etc.) and get the same look and feel for both.
  • The UI is skinnable. You can use Themeroller to roll your own theme, or select an existing theme. For example, I’m using the ‘Redmond’  theme in an application I’m currently building. You can see the Gallery of themes by clicking the ‘Gallery’ tab in the top left corner.  The gallery also shows you what the standard jQuery UI widgets look like. Unfortunately it doesn’t show you other common design elements- but that’s why I’m blogging!
  • You can easily switch to another theme just by changing a single path reference in your applications. You can see this at work by using the Themeswitcher widget, which is easy to embed in your page (just remember you will be connecting to the jqueryui.com website when you use this widget).

Downsides to the Framework

The framework is not without its weaknesses, some of which, over time, I’m sure will be addressed. The major ones I see are:

  • Poor documentation of the purpose behind each selector.  For example:

    .ui-helper-clearfix: Applies float wrapping properties to parent elements

    . What exactly does this mean? And where would you use it? I think I’ve figured it out, by trial and error, but couldn’t the authors write something more meaningful?

  • Reliance on em as the unit of measure rather than pixel. I realize there are lots of advantages to this, but it has its drawbacks too- most notably, when you nest some UI elements you can end up with different font-sizes, due to the use of 1.1em in some cases (this is a multiplier, so in my app I have 1em applied, which results in a font size of 11px, then I have a tab with content. The text in that content comes out at 12.1px (1.1em). If you don’t understand em versus px, try this article. Also, see my post on using 62.5% on a body CSS selector..
  • Incomplete framework. Most notably, tables are not addressed. (I use tables to present database information in business apps). Tables fall outside the regular cascade rules, it seems, so the font size for table content is screwed up. I suggested a simple fix of adding the word ‘table’ to a selector, but that got dismissed as too specific. So whenever you use a table in conjunction with the Framework CSS, you’ll have to add a customized CSS rule, such as this one:
    .ui-widget table { font-family: Lucida Grande, Lucida Sans, Arial, sans-serif; font-size: 1em; }. I could rant about this, and may do in another post… Other selectors are missing, too, such as alternating row colors for table zebra striping. Perhaps they will add this to the Themeroller app, as well as to the CSS Framework API specifications.
  • Sometimes you need other CSS to make things look like they do in the online examples. I ran across this with the Dialog example that shows a form. The form looks really beautiful, but it actually uses several additional selectors besides the ones included in the Framework CSS.  I don’t really think there’s much of a technical alternative here, but it’s something you need to be aware of.

How To Learn About The Framework

I learn about how to use the framework by using the following strategies:

  • Read the official CSS Framework documentation.
  • Try out the widget examples and do a ‘View Generated Source’ or ‘Inspect Element’ with Firebug. This shows you how the UI Widget developers utilized the CSS framework. For example, I noticed that the Dialog widget shows really nice looking Ok and  Cancel buttons, so I inspected them to see which CSS rules had been used. (See my example below).
  • Follow the jQuery UI forum and read books. There’s a new edition of a book on jQuery UI 1.7 that recently (Nov 2009) came out.

Example Using the Framework To Style a Button

Here’s a simple example of using the CSS selectors to style a button. I’m using the Redmond theme here.

I assume you know how to install the jQuery UI library and CSS.  You can grab it here.

Here’s the code:

    <style>
    body {font-size: 62.5%}
    </style>
<button id="cancel" type="button"  class="ui-state-default ui-corner-all">Cancel</button>

Here’s what it looks like:

jQuery UI button in FireFox

jQuery UI button in FireFox

jQuery UI button in Chrome

jQuery UI button in Chrome

jQuery UI button in IE

jQuery UI button in IE

As you can see, FireFox and Chrome each do a nice job of rendering the rounded corners, while IE 8 still doesn’t support this feature (at least, not with CSS).

Explanation of The CSS

I’m using two classes on the button element. This is a common coding technique when using the jQuery UI CSS framework. It results in combining the various selectors of each style in an accumulative manner. The ui-state-default class “Applies “clickable default” container styles to an element and its child text, links, and icons.” For example, we could apply this to a link and get essentially the same effect. This class includes a background image that provides the button coloring. As I mentioned earlier, if you change the theme used in your app, the button will appear in the color of that theme.

The ui-corner-all selector applies a radius (rounded corner) to each of the four corners of the button border. That’s it!

Next Article

In the next article I will show you how to style a div to create a nice looking box with a heading in it.

Articles I’ve Written on IBM i (iSeries) Technology Subjects

I’ve written a few articles in recent years that have been published by MC Press Online, relating to IBM i topics. If you don’t know what the IBM i is (or an AS/400, iSeries or System i), you can stop reading! Here are two lists of links to those articles. The first list is general education. The second is product-specific, related to products marketed by my company. (Articles are ordered by most recent first)

Educational Articles

Product-Specific Articles

Feedback jQuery Plugin

Feedback is a jQuery plugin that lets you send feedback to a user in the form of an info message or error message, associated with any page element. It uses the jQuery UI plugin to determine the default styles of the info and error messages, but you can also use your own styles. Complete details, including demo, documentation and downloads are on this page.

My Favorite FireFox Plugins for Web Development

  • Firebug – debug your applications. An absolute must. Best features:
    • Debugger – step through, over, etc.
    • Console log for monitoring AJAX interactions -shows parms sent, data returned, round-trip time.

  • Web Developer – fantastic CSS diagnostic support. Best features:
    • View generated source – important if your script modifies the original DOM of your page
    • Display Element Information – shows all the properties of an element in a convenient popup. To use, press Ctrl+Shift+F or select menu Information/Display Element Information
    • Edit CSS – lets you edit the CSS selectors in real-time, and shows you the results – almost as you type
  • MeasureIt. Lets you find the height and width of any element or area of the page, in pixels. Helps diagnose CSS issues, for example, when you use combinations of margin, width, padding and border attributes.
  • Codeburner from Sitepoint, one of my favorite online journals (www.sitepoint.com). Integrates with Firebug to provide comprehensive cross-reference information on HTML and CSS. Best feature:
    • Browser compatibility tables

Checked attribute of checkboxes- IE versus FireFox

In FireFox, <input type="checkbox" name="checkme" value="ok" "checked"> results in the checkbox being checked by default. In IE (version 7 – haven’t tried 8), it does not. This is one of the few times FireFox is more liberal than IE, and wrong. The correct code is: <input type="checkbox" name="checkme" value="ok" checked="checked">

See this W3C specification.

It’s a bit difficult to find the rule on this page, but if you scroll down to section 17.4 The INPUT element you’ll see this text for the checked attribute:

checked (checked) #IMPLIED — for radio buttons and check boxes —

Even then, it’s still confusing, because if you click the link for the ‘checked’ attribute, you’ll see it referred to as ‘this boolean attribute’. While it’s correct that it is a switch – either “checked” or nothing, it’s not a true boolean – either ‘true’ or ‘false’. Anyway, this one bit me because I wrote some markup with checkboxes and only tested the page in FireFox. In my test, all the checkboxes were checked, by default, which is what I wanted. The IE users got a different result altogether.

Update: Chrome also requires that you use the correct (strict) syntax.

How To Check or Uncheck all checkboxes in jQuery

This post explains how to set a group of checkboxes to checked or unchecked using jQuery 1.3, by clicking an “All” or “None” button.

First, let’s select our group of checkboxes. I’ve seen some fairly complicated jQuery selectors for finding checkboxes on a page, but it seems to me the easiest thing to do is just assign a common class to each one in a group, even if you don’t define the class in your stylesheets. Like this:

<input type="checkbox" class="selsts" name="selsts" value="E"> Emailed
<input type="checkbox" class="selsts" name="selsts" value="W"> Work in Progress
<input type="checkbox" class="selsts" name="selsts" value="P"> Pending client call
<input type="checkbox" class="selsts" name="selsts" value="R">R-Returned call

the jQuery selector for this is: $(".selsts") .

We could also select all the elements based on their common name, which I think goes like this: $(['name=selsts']) .
But I prefer classes, because you can easily change their names without affecting server-side code that may be dependent on form field names.

Let’s say we have two buttons on our page, using the following markup:

Select: <input type="button" id="allsts" value="All">, <input type="button" id="nosts" value="None">

To make all our checkboxes checked:

$("#allsts").click(function() {
$(".selsts").attr('checked', true);
});

To uncheck all the checkboxes:

$("#nosts").click(function() {
$(".selsts").attr('checked', false);
});

That’s it.

To determine if a checkbox is checked or not, we can loop through the array like this:

$('.selsts' ).each( function() {
var isitchecked = this.checked;
});

Or, individually:

if ($('#somecheckbox').checked == true) { blah blah ... }