A Note On Case Sensitivity

I’m in the process of creating my first Chrome Extension – it’s a version of something which already exists but which seems simple enough to begin with and will have enough challenges to keep me interested. So far it’s already taken me into reading URLs from a tab, opening and closing tabs and communicating with a database.

Ah that last one is worth a post all of it’s own (and there’s one coming up!) and it’s the last one which threw up something which I wasn’t expecting – something having been developing in one way or another for years I should have known better.

You see I think I’m very good at tracking down and finding errors in my code (debuggers are REALLY helpful once you know what the error messages mean) and I can normally pick them up and fix them fairly quickly. But this one bug had me stumped all afternoon yesterday and for some reason it wasn’t picked up by the JavaScript console.

What was happening was I was trying to use an AJAX xhr request to receive a response from a PHP script and was using onreadystatechange to trigger a function to do something. But after many hours of looking the readyState property wouldn’t get past 1 (sent).

There were loads of helpful guides online suggesting all kinds of reasons this might be happening but none of them seemed to fit this scenario. Until I stumbled on a post on Stack Overflow talking about problems with the readyState property. Somebody had pointed out that this developer had used readystate instead of readyState. Note the capital S.

JavaScript is case sensitive so onreadystatechange, which triggers as an AJAX request changes states (1 being sent, 4 being complete) is seen as different from onReadyStateChange. A quick Google for the onreadystatechange and it turned out I was using camel case rather than all lowercase. Oops.

I amended onReadyStateChange to onreadystatechange and what do yo know, the script started functioning as expected. The lesson from this is if something doesn’t appear to be working because something isn’t being called check if you’ve got the case sensitivity correct.

It’s normally caught by an error at runtime (something like undefined) but it wasn’t showing up this time and I have a feeling it’s because JavaScript was listening for a state change but listening using an event which didn’t exist. An interesting thought with event driven code.

Leave a Reply

Your email address will not be published. Required fields are marked *