jQuery interprets NULL parameter to val() call as no parameter

I tried to be smart (no, I was not obfuscating my code) and squeeze the following algorithm into one line of code:

  • Set the field email to the value of cookie user
  • If the cookie user is not present, focus the email field, otherwise focus the pwd field.

The one-liner I (almost) got working is:

if ($("#email").focus().val($.cookies.get("user")).val()) $("#pwd").focus();

The description of how this beast works is left as an exercise for the reader

However, the $.cookies.get function returns NULL if the cookie is not set and the first val call interprets the NULL value as no parameter, returning the current value of the field, not the chainable jQuery object.

Too bad, I had to write two lines of code:

$("#email").focus().val($.cookies.get("user"));
if($("#email").val()) $("#pwd").focus();

Convert Atom-formatted DateTime

The following function converts ATOM (RFC4287) formatted Date/Time string into a VBScript Date variable. You’ll find it useful if you want to process Atom feeds with VBScript/ASP.

Function AtomDateTime(S)
  Dim CompArray,ValueArray,DateVal,TimeString,TimeVal,ZoneSign,ZoneString,I

  CompArray = Split(S,"T")
  If UBound(CompArray) <> 1 Then _
    Err.raise vbObjectError,"AtomDateTime","No 'T' in Atom date/time"
  ValueArray = Split(CompArray(0),"-")
  If UBound(ValueArray) <> 2 Then _
    Err.raise vbObjectError,"AtomDateTime","Atom date part is not a date"
  DateVal = DateSerial(CInt(ValueArray(0)),CInt(ValueArray(1)),CInt(ValueArray(2)))

  TimeString = CompArray(1) : I = InStr(TimeString,"Z") 
  If I > 0 Then
    TimeString = Left(TimeString,I-1)
    TimeVal = GetAtomTime(TimeString)
  Else
    I = InStr(TimeString,"-")
    If I > 0 Then 
      ZoneSign = 1 
    Else
      ZoneSign = -1 : I = InStr(TimeString,"+")
    End If
    If I = 0 Then _
      Err.raise vbObjectError,"AtomDateTime","cannot recognize timezone separator"
    ZoneString = Mid(TimeString,I+1,Len(TimeString))
    TimeString = Left(TimeString,I-1)
    TimeVal = GetAtomTime(TimeString) + ZoneSign * GetAtomTime(ZoneString)
  End If
  AtomDateTime = DateVal + TimeVal
End Function 

The DateTime is converted into GMT time value. You might need to add/subtract your local timezone offset if you want to get local time.

The GetAtomTime function converts the time portion of the DateTime field:

Function GetAtomTime(TS) 
  Dim I : I = InStr(TS,".") : If I > 0 Then TS = Left(TS,I-1)
  GetAtomTime = Timevalue(TS)
End Function

Login to Google Data API

Google Data API has numerous client-side libraries, but not an ASP/VBScript one. Here’s the first routine you need: it authenticates you with the Google API and returns a handle you can use in subsequent calls.

The HTTPCheck is a function that checks the status code before returning to the caller. You could replace if with XRQ.status < 300. You'll find the EncodeFormData function in a previous post.

Dim XRQ ' global XMLHttpRequest object

Function GoogleLogin(UN,Pwd,Svc)
  Dim RQData,I,RT

  GoogleLogin = Null
  RQData = EncodeFormData(Array("Email","Passwd","service","source"), _
    Array(UN,Pwd,Svc,"VBScript-BloggerLibrary-0.1"))

  If Not IsObject(XRQ) Then Set XRQ = CreateObject("Microsoft.XMLHTTP")
  XRQ.open "POST","https://www.google.com/accounts/ClientLogin",false
  XRQ.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
  XRQ.send RQData
  If HTTPCheck(XRQ,"Google login response", _
    "https://www.google.com/accounts/ClientLogin") Then
    RT = XRQ.responseText
    I = InStr(RT,"Auth=")
    If I = 0 Then wr "Google response has no AUTH data" : Exit Function
    RT = Mid(RT,I+5,Len(RT))
    I = InStr(RT,Chr(10)) : If I > 0 Then RT = Left(RT,I-1)
    GoogleLogin = RT
  End If
End Function

The inconsistent consistencies are driving me crazy

Here’s a simple question: what’s wrong with this code?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns:xf="http://www.example.com/common/xslforms">
...
<input type="button" value="X" id="tb_0" onClick="callX(0)" />

Among other things, this is not valid XHTML (as claimed in DOCTYPE) because the onClick attribute should be spelled in all-lowercase (onclick).

Now the trick question: why am I so annoyed by this code? Because it works in IE7, FF2 and FF3 if the server serves HTML to the client and fails only in FF3 if the client performs XSLT transformation using a stylesheet similar to this one:

<?xml version="1.0" encoding="utf-8" ?>
<xsl:stylesheet
version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:output method="html" encoding="utf-8"
  doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN" doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"/>

<xsl:template match="/">
  <html xmlns:xf="http://www.plezanje.net/common/xslforms">
…
  <input type="button" value="X" id="tb_0" onClick="callX(0)" />
…
</xsl:template>

The ever-more-crazy implementation of XSLT in Firefox will persuade me to:

  • Stop using client-side XSLT transformations or
  • Stop supporting Firefox and recommend everyone to use IE or Chrome.

Generate HTML form data in VBscript

Sometimes you have to post form data in an AJAX call started from server-side ASP script (or WSH script). The following VBScript functions will return well-formed form data that you can use with the application/x-www-form-urlencoded MIME type:

Function URLEncoded(V) ' … private
  Dim CC,I,Enc
  Enc = ""

  For I = 1 To Len(V)
    CC = AscW(Mid(V,I,1))
    If (CC >= 48 And CC < 58) Or (CC >= 64 And CC < 90) Or (CC >= 97 And CC < 124) Or CC = 95 Or CC = 45 Or CC = 46 Then
      Enc = Enc & Mid(V,I,1)
    Else
      Enc = Enc & "%" & Hex(CC)
    End If
  Next
  URLEncoded = Enc
End Function

Function CreateFormField(F,V) ' … private
  CreateFormField = F & "=" & URLEncoded(CStr(V))
End Function  

'
' EncodeFormData: Return form data for a POST request
'
' Input: N – array of form field names
'        V – array of form field values
'
' Return: encoded form data
'
Function EncodeFormData(N,V)
  Dim I
  For I = LBound(N) To UBound(N)
    If I <> LBound(N) Then EncodeFormData = EncodeFormData & "&"
    EncodeFormData = EncodeFormData & CreateFormField(N(I),V(I))
  Next
End Function

How crazy can it get: IE does not set the Referer field if the page was built via client-side XSLT

Some of my web sites rely on client-side XSLT transformations, triggered with the <?xml-stylesheet > processing instruction in the XML document sent by the server. A long time ago I've noticed that some of the utility functions perform differently in IE than in Firefox and finally decided to figure out what's going on. The results are "fascinating": when you click on a link in a page generated with client-side XSLT transformation, IE does not set the Referer: field in the HTTP request. I can only congratulate the coders ... you have an amazing mindset ... not to mention the QA department.

OMG: jQuery tag selectors are case sensitive

… if you use Firefox and client-side XSLT transformations. This is the scenario:

If you use tags in jQuery selectors, for example $(".pulldownMenu P A").click(handler), the tag names are case insensitive if you use IE or server-side transformation with Firefox but become case sensitive if Firefox performs client-side transformation regardless of xsl:output settings. To ensure your jQuery code works in all cases, write exactly the same tag names in jQuery selectors and XSLT stylesheet.

Detect whether your browser has a working XSLT implementation

After I’ve finally managed to persuade IE7, FF and Transform jQuery plugin to work with my XSL documents, I’ve started testing the other two browsers I have: Opera and Chrome. The latest release of Opera might occasionally work. Chrome fails (as expected) as it doesn’t support xsl:import. Welcome to the next round of browser incompatibilities.

I’ve decided to ignore Chrome until the great minds @ Google decide to implement XSLT properly. Visitors using it will have reduced experience … but of course I have to detect whether I should use XSLT or not.

Here’s a small Christmas gift if you have similar issues: a jQuery extension that checks whether the current visitor can use XSLT transformations.

jQuery.xslt = {
  need: function(success,url,xml) {
    var componentCount = 0;
    var xslt;
    var el;
    var debug=1;
    
    function tryTransform() {
      if (typeof(xslt) != 'object') return; // XSL did not parse into XML object
      var html = $.transform({xmlstr: xml, xslobj: xslt, async: false});
      alert("html="+html);
      if (!html) return;
    }

    function gotScript() {

      function transformFail(html,xsl,xml,obj,ex) { 
        if(debug) alert ("$.xslt.need failed:"+ex.message); }
    
      function transfromDone(html,xsl,xml,obj) { 
        $.xslt.has = html.search($.xslt.expectedResult) >= 0;
        if ($.xslt.has && success) success();
      }
      
      el = $("<div>");
      el.transform({xmlstr: xml, xsl: url, 
        success: transfromDone, error: transformFail});
    }
    
    url = url ? url : $.xslt.defaultURL;
    xml = xml ? xml : $.xslt.defaultXML;
    $.getScript($.xslt.transformScript,gotScript);
  },
  has: false,
  
  defaultURL: "/forms/xml/static.xsl",
  defaultXML: "<section />",
  transformScript: "/common/js/jquery.transform.packed.js",
  expectedResult:  /table/i
}

The extension implements a simple function and a property: $.xslt.need() and $.xslt.has. You can pass the URL to the sample XSL document and the sample XML markup to the need function; it also supports a success callback to tell you whether you should install XSL-related action handlers.

The need function loads the jQuery Transform plugin (reducing the load time if the page does not need the XSLT functionality) and tries to transform a sample XSL document. The sample transformation should be as complex as possible: you should use xsl:import, xsl:include or the document() function if you use them in other transformations.

You could change the default parameters in the source code or write a setup function.

IE7, xsl:import and jQuery Transform plugin

After exhausting all other (more convenient from my perspective) approaches, I’ve had to admit that there’s only a single solution that allows you to include/import XSL stylesheets with the jQuery Transform plugin if you want to:

  • Use XSL documents from another directory on the Web server.
  • Use xsl:import or xsl:include in the XSL documents.
  • Have a reliable cross-browser implementation.

The solution, as you might have guessed, is to use the URL pointing to the XSL document in the call to $.transform (the xsl parameter). And just in case you’re wondering why I had to try everything else: I wanted to use the $.transform() call to get the transformed HTML without the delay incurred by setting the async parameter to false.

Xsl:import fails when using XSL object in $.transform

After the initial set of xsl:import related problems I’ve encountered running jQuery Transform plugin in IE7, I’ve tried to pass the XML document as string (using the xmlstr parameter) and XSL as parsed object (using the xslobj parameter) returned by the $.get call. Works perfectly in FF, fails miserably in IE7. The error message indicates that the imports requested with xsl:import don’t work at all. Back to the drawing board …

Import/include problems in jQuery Transform plugin

I started testing the jQuery Transform plugin with a set of pretty convoluted XSLT documents that I use on the target web site, which relies almost exclusively on browser-side XSLT transformations. All server responses are initially encoded as XML and transformed on the server only if the browser does not support XSLT (or if a spider has come to visit us). Not surprisingly, the XSLTs are heavily loaded with xsl:import and xsl:include statements.

Initially, I tried to control as much as possible: read XML and XSLT into strings and perform the transformation when everything has been collected. This approach fails miserably in IE7. The reason is simple: if I pass XSLT source or parsed XSLT object to the $.transform routine, the routine tries to fix xsl:import and xsl:include references using the current web page’s URL as the base reference, which is wrong if the stylesheet has been loaded from another directory.

Conclusion: if you read XSL documents from another directory and pass them as string to the $.transform routine, make sure you use absolute references in import/include statements.

jQuery Transform plugin

Finally I found some time to start working on XSLT transformations in jQuery framework. I may be completely wrong, but I decided to go with the Transform plugin. If anyone has found a better plugin, I would highly appreciate your feedback :).

Refactoring a menu: remove inline CSS

If you’re new to this series, read the “Refactoring a simple menu” and “Changing the background images” first.

The next step in HTML/CSS refactoring was to clean up the very ugly HTML code … I don’t know what I was thinking at that time; the menu full of repetitive inline CSS is plainly stupid.

Looking at the HTML code, it’s obvious that:

  • The row buttons are independent DIV elements;
  • Each row button has a P child and potentially a DIV child (holding the pull-down menu box).
  • The pull-down menu box has P children that are styled identically to the P elements in the row buttons.

So here’s a very obvious CSS solution:

  • Mark the row button DIV elements with a class (rowMenu).
  • Define styling for P, A and DIV children of the DIV.rowMenu elements.

The resulting CSS is pretty simple …

DIV.rowMenu { float: left; position: relative; z-index: 100; }
DIV.rowMenu DIV { position: absolute; display: none; }
DIV.rowMenu P { … original btx170 definition … }
DIV.rowMenu P.down { … btx170_down definition … }
DIV.rowMenu A { color: #000; text-decoration: none; }

… and so is the cleaned-up HTML code:

<div class="rowMenu" id="IDAHYJQB">
  <p><a href="/climbing/myClimbs/myClimbs.asp">First page</a></p>
</div>
<div class="rowMenu" id="IDAKYJQB">
  <script>menuRegister('IDAKYJQB')</script>
  <p id="IDAKYJQB_main"><a href="javascript:menuClick('IDAKYJQB')">Add ...</a></p>
  <div id="IDAKYJQB_sub">
    <p><a onclick="menuSelect('IDAKYJQB')" 
        href="/climbing/myClimbs/myClimbs_add.asp">New entry </a></p>
    <p><a onclick="menuSelect('IDAKYJQB')" 
        href="/climbing/myClimbs/myClimbs_editWall.asp?a=add">Edit</a></p>
    … more …
  </div>
</div>

Next task: get rid of superfluous element IDs.

Refactoring a menu: Changing the background images to borders

Before reading this: read the “refactoring a simple menu” post to get the background information.

One of the stupidities I did in the original menu implementation was to use CSS background images for simple buttons that could be implemented equally well with CSS borders. It would be hard(er) to get rid of background images if I would have had rounded corners or shaded button background, but I had none of those. So here’s the new CSS definition, replacing images with borders.

The new CSS has another great side-effect: the button sizes are specified in EMs, not in pixels, so the buttons get resized automatically if you change points-to-pixels ratio.

.btx170,.btx170_down {
  overflow: hidden; cursor: pointer;
  padding: 0 0 2px 0; margin: 0 0; text-align: center;
  font-family: Verdana, Arial, Helvetica, sans-serif; 
  font-weight: 700; font-size: 8pt; }
  
.btx170, .btx170_down { width: 16em; }
.btx170 { background-color: #FFCE63; border: 2px outset #FFCE63; }
.btx170_down, { background-color: rgb(255,156,0); 
  border: 2px inset rgb(255,156,0); }

Next task: Remove inline CSS

Refactoring a simple menu

Years ago I had to implement a drop-down menu. Nothing fancy; no open-on-hover magic, but a simple line of buttons with drop-down boxes that would open on clicking the button.

There were just a few annoying details: clicking a top-row button should obviously open a drop-down box, but also change state the button’s state to “depressed” and close any other open drop-down box (and change the state of corresponding buttons).

Here is my five-year-old HTML code …

<div style="float: left; position: relative; z-index: 100;" id="IDAHYJQB">
  <p class="btn170">
    <a href="/climbing/myClimbs/myClimbs.asp">First page</a>
  </p>
</div>
<div style="float: left; position: relative; z-index: 100;" id="IDAKYJQB">
  <script>menuRegister('IDAKYJQB')</script>
  <p class="btn170" id="IDAKYJQB_main">
    <a href="javascript:menuClick('IDAKYJQB')">Add ...</a>
  </p>
  <div style="position: absolute; display: none;" id="IDAKYJQB_sub">
    <p class="btn170">
      <a onclick="menuSelect('IDAKYJQB')" 
        href="/climbing/myClimbs/myClimbs_add.asp">New entry </a>
    </p>
    <p class="btn170">
      <a onclick="menuSelect('IDAKYJQB')" 
        href="/climbing/myClimbs/myClimbs_editWall.asp?a=add">Edit</a>
    </p>
    … more …
  </div>
</div>

… the corresponding CSS …

.btn170, .btn170_down { background-repeat: no-repeat; 
    width: 170px; height: 20px; line-height: 18px; overflow: hidden; 
    padding: 0 0; margin: 0 0; text-align: center;
    font-family: Verdana, Arial, Helvetica, sans-serif; 
    font-weight: 700; font-size: 11px; }

.btn170
  { background-image: url('images/button_170.gif');  }   
.btn170_down
  { background-image: url('images/button_down_170.gif'); }

… and JavaScript code …

var topMenuItems = [] ;

function addClass(id,sfx) {
  var se = getElement(id) ;
  if (se.className.indexOf(sfx) < 0) se.className = se.className + sfx ;
}
function removeClass(id,sfx) {
  var se = getElement(id) ;
  var i = se.className.indexOf(sfx) ;
  if (i > 0) se.className = se.className.substr(0,i) ;
}

function menuShow(id) {
  var se = getElement(id) ; se.menuActive = true ; 
  showElement(id + "_sub") ; addClass(id+"_main","_down"); }

function menuHide(id) { 
  var se = getElement(id) ; se.menuActive = false ; 
  hideElement(id + "_sub") ; removeClass(id+"_main","_down"); }

function menuGo(id,l) { menuHide(id); location.href = l; }
function menuSelect(id) { menuHide(id) ; }

function menuClick(id) {
  var i,se ;
  se = getElement(id) ;
  if (se.menuActive) {
    menuHide(id) ; return ;
  }
  for (i = 0 ; i < topMenuItems.length ; i++) {
    if (topMenuItems[i] != id) menuHide(topMenuItems[i]);
  }
  menuShow(id) ;
}

function menuRegister(id) { 
  topMenuItems[topMenuItems.length] = id ;
}

I will not try to explain what this code does, as it’s way too painful. As I’ll walk through the refactoring process, I’ll show you the changes I’ve made and the stupidities in the original code.