Archive for the ‘Javascript’ Category
The New Lightbox 2
Posted in Javascript on November 17th, 2006
As I stumble through the web today, I found a new version of the famous Lightbox JS.
A quick look at the examples and I was impressed with the improvements. I know how hard it is to fade an entire page without flickering (actually, I haven’t worked that out yet!).
onChange vs onClick Event
Posted in Javascript on November 14th, 2006
Recently I was working on a piece of code that would show or hide particular elements based on a Radio option’s ‘checked’ property.
I used the onChange event to fire my code, because that’s what I was doing to the radio option, right?
In a way yes it worked – in every browser but IE. After reading a post about browser inconsistencies I learned that IE doesn’t fire the onChange event, until after I lose focus of the option I just changed – which just doesn’t make sense!
Here’s a quick example of what I’m talking about. Try this in different browsers.
Needless to say, using onClick instead fixed the problem. It seems that onChange still exists for the user who sometimes prefers not to use a mouse when navigating a website. For the purposes of the few, I try to use both events (providing the function to be called checks the status of things to avoid double handling).
Snippets Online
Posted in Javascript, PHP on November 7th, 2006
Today I launch another small database site.
Snippets.jc21.com is a database of useful pieces of code from any langauge you may use.
I often use different computers to code, or sometimes forget to backup my snippets before a re-format. So I made this site to keep a track of things.
The site allows full search and browsing capabilities, so you can easily find what you’re looking for. There are only a few gems there at the moment, but will be growing each day.
If you have any useful snippets or functions that you would like to share, submit them.
Yahoo helping Web 2.0 evolve
Posted in Javascript on November 3rd, 2006
Recently it was brought to my attention that I should use the Yahoo UI Library to solve a problem I’ve had. Having used these tools when they were first released I thought they were cool at the time. Now I still think they’re cool and well documented.
I am always cautious building sites relying on Javascript because of all the things that can go wrong from browser to browser. Lately I’m learning towards the ‘if you’re browser doesn’t support my site, it’s time to upgrade!’ line of thinking.
Information based sites don’t need to be Web 2.0 enhanced, but now we’re building Applications that do stuff! I want to drag ‘n’ drop things and watch cool animations when I delete something.
Where was I… Yahoo UI and the Yahoo Design Pattern Library are helping to make our lives easier. If you don’t have a degree in Interface Programming, at the very least take a look at the Design Patterns. You’ll soon discover what Usability is all about.
How to use Sarissa Ajax Library
Posted in Javascript, Tutorials on September 7th, 2006
I’ll spell it out for you. Or even better, I’ll just give you the code! This is the first part of a tutorial covering the Front-end browser part of Ajax’ing and the Back-end part of sending data with PHP. The second part can be found here.
I am only going to explain the minimums for accomplising this goal. A bigginers lesson if you want. I won’t cover more complex options as I don’t need to use them myself, yet.
The Sarissa Ajax library is my choice for Ajax’ing for a few reasons:
- It’s small (11.8kb!)
- Cross browser compatible and
- Escapes the information received nicely
My tutorial will only cover XML request with Sarissa.
What you need to get started:
- A web development server (consider Wamp if you’re using Windows)
- Latest versions of your browser (IE 7 not required, the latest IE 6 is fine)
- The Sarissa Library
- Cross Browser X Library javascript functions – Optional, for DOM functions you may use.
At this point I should mention that if you’re reading this article, I assume you’re serious about writing your powerful Web 2.0 applications. If you don’t know your DOM or Javascript language very well, I suggest you take a look at this Sitepoint book. The sample chapters are free and they will help you out quite a bit. Purchase the book if you like it.
So, let’s view the major function for our javascript code, assuming you’ve linked to sarissa.js in your document:
// getUrl // Will initate the http request for data. function getUrl(url,fn) { if (url && fn) { var xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET", url, true); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4) { fn(xmlhttp.responseXML); } }; xmlhttp.send(''); } else { alert('url or function not specified!'); } } // trim functions // will trim whitespace from strings String.prototype.trim=function(){ return this.replace(/^\\s*|\\s*$/g,''); } String.prototype.ltrim=function(){ return this.replace(/^\\s*/g,''); } String.prototype.rtrim=function(){ return this.replace(/\\s*$/g,''); } // CheckResultIsOk // Will check the XML data you've return for <error_code>x</error_code> // and returns the error to the user if found. function checkResultIsOk(xml) { if (!xml) { //xml data was empty. Result was not ok. return false; } if (xml.getElementsByTagName('error_code')[0].firstChild.data && Math.abs(xml.getElementsByTagName('error_code')[0].firstChild.data.trim()) > 0) { //error has been supplied alert('Error ' + xml.getElementsByTagName('error_code')[0].firstChild.data + ': ' + xml.getElementsByTagName('error')[0].firstChild.data.trim()); return false; } else { //no errors! return true; } }
Download this code: sarissa_tute_1.js
The functions are very simple.
- getUrl takes an URL, and a function name before opening a http request. The URL should point to the file on your server, from which XML data would be returned. The function name is just the name of a function you’ve already specified. This function gets called once the XML data has been returned. And you’ve probably guessed I like error checking. The alert reponse can be omitted – it’s just there for our testing purposes.
- trim functions are a few ingenious pieces of code that will save you years of headaches. As some XML documents are formed, whitespace can occur around the data within the tags. These functions can remove this from your strings.
- checkResultIsOk will check your XML data that you’ve returned for any specified errors. Of course, this only works if your XML document contains a valid error_code tag with an error number in the data, zero being no error. I started using this method of checking so that I could return errors with my back-end system to the user in a friendly manner. Setting an error tag with a description in your XML will also display that to the user.
Believe it or not, but that’s the hard part over. All you need to do now is create your functions to request your data, and additional callback functions to process the data. Here’s an example of a request function:
// ajaxGetItems // Called from clicking a link or button on your page function ajaxGetItems() { //send the request var filetouse = '_ajax.php?mode=getitems'; getUrl(filetouse,cbGetItems); }
Download this code: sarissa_tute_2.js
Easy wasn’t it? Notice you can include GET variables in your request. So if your XML document is a dynamic script (as in part two of this tutorial) you can control some aspects of the script. Also notice that when you specify the function name for getUrl, you don’t wrap it in quotes, and you don’t add () to the end of it, otherwise the function would be executed right there at that point in the code.
So let’s assume this is the XML data that has been returned:
<?xml version="1.0" encoding="iso-8859-1"?> <xmlresponse> <item_count> 4 </item_count> <item> <id> 15 </id> <name> Finger Bun </name> <price> $0.80 ea </price> </item> <item> <id> 16 </id> <name> Donuts </name> <price> $0.50 ea </price> </item> <item> <id> 17 </id> <name> Apple Pie </name> <price> $1.20 slice </price> </item> <item> <id> 18 </id> <name> Double Choc Chip Cup Cakes </name> <price> $1.00 ea </price> </item> <error_code> 0 </error_code> </xmlresponse>
Download this code: sarissa_tute_1.xml
So in our document we have an item_count tag, 4 items tags with sub tags, and our error_code tag. Let’s see how our callback function would handle this:
// cbGetItems // Called when the data from ajaxGetItems has been retrieved. function cbGetItems(xml) { //check result is ok if (checkResultIsOk(xml)) { //get the item count var item_count = Math.abs(xml.getElementsByTagName('item_count')[0].firstChild.data.trim()); //get the items var items = xml.getElementsByTagName('items'); for (i=0;i<items.length;i++) { //send an alert of the data received alert (i + " Data recieved:\\n" + "id: " + items[i].getElementsByTagName('id')[0].firstChild.data.trim() + "\\n" + "name: " + items[i].getElementsByTagName('name')[0].firstChild.data.trim() + "\\n" + "price: " + items[i].getElementsByTagName('price')[0].firstChild.data.trim() + "\\n"); } //end i for } //end check result } //end function
Download this code: sarissa_tute_3.js
The first things the function does is check the data for an error with the checkResultIsOk function. If it passes, we extract the data. The item_count tag isn’t being displayed to the user, I’ve only put it in there to show you how to extract a single tag (that doesn’t have an ID). Next we get all the items tags, iterate through them and display the data in alert popups. You can do whatever you like with the data I’ve used in these alerts.
So there you have half of it! Using Sarissa to retrieve XML data and do something with the data, all with cross browser functionality. Now take part two of the tutorial and learn How to dynamically return XML data using PHP
Technorati: javascript, ajax, xml, tutorial, sarissa