Posts Tagged ‘javascript’

Server-logging client-side javascript errors

Wednesday, May 25th, 2011

There are several examples of this already on the net, but this technique came in handy on a recent site I programmed. The concept is that you overwrite any existing browser reaction to the window.onerror event with your own function that sends an XMLHttpRequest containing gathered error information to a server-side script which logs that information to a file or database.

The user-experience as defined by the designer & client called for virtually every page to have a “dashboard” feel, whereby a site visitor could click buttons & links and the main content area of the page would be replaced (typically via innerHTML.)

Cross-browser debugging nearly became a serious issue; it was like a wild shoot-out in a digital saloon, with AJAX bullets flying through HTML-tag-cowboy hats and ricocheting off the piano player’s include files.

I got pretty much everything straightened out, but we still had the rare non-responsive button or empty content screen. So as we opened the site to a private beta, the following bit of PHP helped the browsers with issues call attention to themselves.

echo "<script>
window.onerror = function(msg, err_url, line){
 var params = 'jserror=1&msg=' +msg+ '&url=' +err_url+ '&line=' +line+ '&ua={$_SERVER['HTTP_USER_AGENT']}';
 whateverAjaxCallYouUse('action.php?'+params);
</script>";

With the increasing reliability of document.activeElement you could conceivably get more detailed information about the page element which caused the problem, however in my case I was only interested in the error messages themselves. In the untested example below, I create a string of JSON text from the activeElement‘s attributes.

var curr = (document.activeElement) ? document.activeElement : false;
if(curr){
 var json_string = '{' +
  ' "element" : "' + curr +
  ' ","tagname" : "' + curr.tagName +
  ' ","name" : "' + curr.name +
  ' ","id" : "' + curr.id +
  ' ","parent" : "' + curr.parentNode +
  ' ","href" : "' + curr.href +
  ' ","src" : "' + curr.src +
  ' ","onclick" : "' + curr.onclick +
  ' ","onfocus" : "' + curr.onfocus +
  ' ","onblur" : "' + curr.onblur + '"}';
}

Or something to that effect, there’s probably a smarter way to do it.

Obviously, this suppresses any normal error reporting in the browser so you’ll want a way to deactivate this behavior for when you’re debugging as you won’t see any errors yourself. In my case, since the site was decently MVC’d it was easy to not echo this function based on whether the appropriate administrator variables were set in the $_SESSION array.

Javascript: Abbreviated DOM methods

Wednesday, May 18th, 2011

<rant>As a foolishly ardent DIY-er AND a programmer I often try to avoid using third-party libraries, as if my “real programmer” credibility depended on complete self-reliance.

This is especially a nuisance when crafting modern interactive websites, as it’s becoming increasingly difficult to avoid libraries such as jQuery.

For me, though, it’s not about some idealist notion of authorship but rather it boils down to my need to understand the code I’m deploying. If I am not getting an expected result, and am including some third-party library, it can be hard to tell where the train went off the rails (sorry, sometimes I don’t have time for breakpoints & stack traces when I’m trying to push attractive & valid code to the browser from what is often the meat & potatoes of a site project: the back-end code in a template system or CMS.

Well this year I finally got around to de-obfuscating the jQuery library and began picking apart how it works.
This is a really important step in deciding to seriously use a tool that I recommend to every practitioner of every craft. Don’t get me wrong, jQuery has some fabulous docs, but mentally understanding the “Why” behind the way things is just as liberating as a complete list of functions & methods.

One way to look at a powerful Javascript library such as jQuery is to canonize it mentally into js, and erase the difference in your mind. That probably works for some people; I don’t think I can do that. There are times where I can imagine not needing the extra baggage of the whole of it for one or two functions.</rant>

Point in case:

On a site which wasn’t already using jQuery, I had need of some considerable DOM manipulations; creating & removing elements, applying additional style, and modifying hrefs. All of which are provided simply by javascript, except that the names of the methods are so freaking long! Come on, you know what I mean. Even IF you’re development environment has an auto-completion feature (I use Notepad++, and the shortcut is CTRL+ENTER, but it’s slower to look through the list and down-arrow to the desired item than it is to just keep typing) document.getElementById(‘…’) is just too damn long.

You gotta admit, there’s something sexy about $(‘#…’). C`est la vie, right?

So here’s what I did, it worked for me, your mileage may vary. Essentially, as a preamble to all the rest of the code, we abbreviate those long names by assigning an anonymous function to a given variable name, like so:

$ID = function(f){return document.getElementById(f);};
$NAME = function(f){return document.getElementsByTagName(f);};

Then, merely use them like this:
var e = $ID('some-element');
alert(e.innerHTML);

Of course, when you really need to boogie, you’ll need access to elements’ class attributes, so:

$CLASS = function(clsName){
 var classy = new Array();
 var pool = document.getElementsByTagName("*");
 for(var i = 0;i < pool.length;i++){
  if(pool[i].className.indexOf(" ") >= 0){
   var classes = pool[i].className.split(" ");
    for(var j = 0;j < classes.length;j++){
    if(classes[j] == clsName){
     classy.push(pool[i]);
    }
   }
  } else if(pool[i].className == clsName){
   classy.push(pool[i]);
  }
 }
 return classy;
}

Adventures in JavaScript

Wednesday, November 5th, 2008

My JavaScript muscles feel just a little tighter lately, thanks to my job. At least, compared to how they were a week ago when I was just getting started with the task of formalizing our budget. What started out as a way to ensure our company was “recession-proof” (not that our organization managed to reap any real benefits from the “good times”) has turned into a major all-consuming crusade to ensure our success.

The task of gathering the necessary data from various computer systems & paper records would, under normal circumstances, be fairly straightforward. Unfortunately, there is the dark ages: the period of time our company wasted attempting to appease to a hopeless, outdated, expensive and disabling petulant child of an Inventory/Financial software package. Extracting information from this opaque mystery is both time-consuming and painful.

The other problem I have been facing is a chart of accounts (both in the aforementioned train-wreck, and in its replacement which we have been using for a full fiscal year) which lacks some of the granularity a leader would need to make good decisions & steer the ship away from the rocks.

Now that I’ve compiled most of what is needed, I needed to make sure it would be used. The eyes of some in the staff tend to look a little glassy after being exposed to only a few “numbers” (indicator ratios, statistics, bank balances), so it’s important that:

1. engage and interact with the product; that I provide not merely information but a tool that creates comprehension, provides answers and pushes the user to question further; and:
2. provides an organized & clean interface which doesn’t distract the user.

By the way, The Visual Display of Quantitative Information, is available on amazon for those who are working on their Christmas shopping ;)

sdf

Awesome book, though I would settle for Visualizing Data by Ben Fry

After a couple of gigantic spreadsheets and one attempt at an OpenOffice Access database, and not feeling particularly good about the results, I decided to deploy it as a web app over the company intranet running on my workstation’s web server. It was looking pretty good, but I’m not fantastic with ajax-style interactivity so it was still half-baked. That’s when I came across ExtJS, which has sped up the production & increased the quality of the application in most areas, but the learning curve for the massive, object-oriented & JSON-related JavaScript library has been hellish.

Here’s a screen shot of what it’s shaping up to look like:

I’m really learning a lot from this entire project process in part because, if anyone else in our small business is able to handle any of these tasks (I’m thinking of the owner, manager & the bookkeeper as 3 people under whose jurisdiction this might fall) they sure aren’t stepping up to the plate, and I am receiving absolutely no guidance or help in creating a sustainable (company staff will be able to use this tool ad infinitum once it is finished) way for to keep our heads above the water in hard times. I’m having to learn new techniques & terminology, analyze and discover trends that can be used to lead.

It’s a very tiring process, so I hope it pays off and I retain some wisdom from the whole experience.