JSON vs. XML: What Should You Use?

Lots of people have asked me this question: which is better when loading data via an ajax request? JSON is my favorite. I’m going to try and explain the benefits of JSON over XML.

From the start, JSON is already has a leg up on XML for one reason: it’s faster. To read XML you need to parse it, read the nodes, attributes, and child nodes in the XML document, and then use the data that you’ve found.

In jQuery the easiest way to do that is to use the built-in ajax functions to call the XML and use the each function to loop through all the nodes. The each function is nice, but is much much slower than a for loop. Just imagine what happens when we have an XML document with multiple levels of nested nodes you need to get at. You end up with multiple nested $.each functions and without much trying, you end up with a script that crawls. With JSON it’s easy to get at the data since its already native javascript. No parsers or proxies necessary–all you need to do is loop through the data, fast and simple. That’s one point for JSON.

There are aspects of XML that people point to as reasons to use it. First, XML is both human and machine readable. It is nice to see what data is being returned just by viewing the source, but that problem is solved by having good documentation, including an example of the JSON that will be returned. Also, being a front-end developer, I spend a lot of my time reading javascript anyway. I find it just as easy to read as XML, it’s just different.

Another good reason to use XML is that it’s widely available. Lots of websites offer APIs to get at their public (and sometimes private) data, and I usually find the returned format of these APIs are often either XML or JSON. However since XML has been around longer than JSON, there is simply more XML out there.

Sometimes you might find yourself in a situation where you don’t have JSON as an option. So do you submit to the API gods and slow down your site and just use the XML? Why do that when you can write the API yourself! This is where some server side skills come in handy. It’s super easy to load an XML document via PHP and print out the data in whatever format you need it to be in.

So in conclusion, you should be using JSON every chance you get.

Using Advanced Segments in Google Analytics to Separate Outgoing Links and Downloads from Pageviews

If you’re like me, you installed the Google Analyticator plugin for your blog or added some other javascript so you could track what outgoing links where clicked. You will have extra pageviews showing in your Google Analytics account that are what I call “ghost pages.” These pages don’t really exist–they are just place holders for the clicks to other sites or your downloads. To get a more accurate number of pageviews, you can use Advanced Segments to create a new segment that will remove these ghost pages. So go log into your Google Analytics account and let’s get started.

Creating the Segment

  1. Make your way to the dashboard for the site you are tracking.
  2. When you reach the dashboard, you will see a settings section on the left. Click the Advanced Segment(beta) link.

    Dashboard

  3. There will now be a link in the upper right that says “Create new custom segment.” Click that to start your new segment. You should now be on a page that looks like the one below.

    Create Segment

  4. Under the Dimensions header on the left it’s probably green. There is a section for content. Pop that open to reveal a list of options.
  5. Drag the Page box onto the box on the right that says “dimension or metric.” Then select “Does not start with” from the drop down that appears under the Condition header. Put “/outgoing” in the Value text area. This gives you a filter that will get all pages that do not start with “/outgoing”
  6. Now you’ll need to make another filter in this same segment that also removes the downloads. Click the ‘Add “and” statement’ link.
  7. You will now have another “dimension or metric” box. You will want to repeat step 5 but change “/outgoing” to “/download” or whatever you use to mark your downloads.
  8. Test your segment with the test segment button on the bottom right side of the page.
  9. Now give your segment a name and hit “Create.” I used “- outgoing/download” as a name.

The finished segment should look like this before you hit create.

Finished Segment

Using the Segment

  1. Make your way back to the dashboard for your site.
  2. Directly above the date picker on the right in the gray menu box there is a drop down labeled Advanced Segments. Click the drop down to open the Advanced Segments options.

    Select Segment

  3. Under custom segments, click the check box next to your new segment you just created. Also leave the all visits default segment checked if you would like to see your unfiltered results.

    Segment Options

  4. Hit “Apply” and that is it.

Once all this is done you will be able to quickly find a more accurate count of pageviews.

Site Usage

Using jQuery and XML to Populate a Drop-Down Box

Building on the post Reading XML with jQuery, I have modified the success function to parse the XML data and load it into a drop-down box. You can get the demo files from Reading XML with jQuery here. Once you download and unzip the demo files, open the index.html in your favorite editor. Then remove all the HTML between the body tag and also all the jQuery in the success function. I also changed the page title to “Using jQuery and XML to Populate a Drop-Down Box Demo.”

Source Demo Reading XML with jQuery Source

Continue reading “Using jQuery and XML to Populate a Drop-Down Box”

Reading XML with jQuery

Welcome to my first of many articles for Think2Loud! Today I thought I’d start with something simple that will lead into several other topics. So here we go, head first into reading XML with jQuery.

The first step is making sure you have jQuery included on your page.

Second, you should check the XML file you are going to read and make sure it’s free of errors. If you are unfamiliar with XML synatax, check out the W3School’s rules on XML syntax. The file I’m using for this example is just a listing of some Web sites I enjoy.

Finally, you just need to tell jQuery to read the file and print out the contents. Start by adding the document.ready function to the page.

$(document).ready(function(){

});

Continue reading “Reading XML with jQuery”

Build an Unsupported Browser Warning with jQuery

Over at CSS-tricks there’s an article about blocking Internet Explorer 6. If the IE 6 Blocker Script is a little too extreme for you, check out what I use on client web sites.

Trying to get someone to upgrade, without being overly aggravating, can be tough. This script accomplishes this by adding a warning box across the top of the site with an option to hide the message. The script uses cookies, so if someone hides the warning it will not come back until they restart their browser. This way, even with an unsupported browser, they can remove the warning and use your site as they wish.

Source Demo (Firefox is also unsupported for the Demo)

Initial Setup

To get started you need to include jQuery and the badBrowser script in the header. The script does the browser detection. This allows for screening of multiple browsers if you like. I just set it up for IE 6 and below.



So whats in the badBrowser.js file?

The first thing you will see is the badBrowser function. This function checks for the browsers that you want to show the warning on. It uses jQuery’s built-in utilities for browser checking. The function returns true if it’s an unsupported browser and returns false if it’s not.

function badBrowser(){
	if($.browser.msie && parseInt($.browser.version) <= 6)
             {return true;}
	return false;
}

Next we have our functions to Get and Set our cookie. The Set function creates a cookie with the name and value of what you pass it. The Get function returns the value of a cookie based on the name you pass into the function. If there is no cookie with that name, it returns an empty string. I am not going to go into the finer details of these functions, but if you'd like to read more about JavaScript cookies check out: http://www.quirksmode.org/js/cookies.html

The Set Function:

function setBadBrowser(c_name,value,expiredays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" + escape(value) +
        ((expiredays==null) ? "" : ";expires=" +
        exdate.toGMTString());
}

The Get Function:

function getBadBrowser(c_name)
{
if (document.cookie.length>0){
   c_start=document.cookie.indexOf(c_name + "=");
   if (c_start!=-1){
    c_start=c_start + c_name.length+1;
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
    return unescape(document.cookie.substring(c_start,c_end));
    }
}
return "";
}

Now with our helper functions all set up we can do some real work. We're going to have an if statement that calls the browser check and also checks to see if our cookie has been set.

if(badBrowser() && getBadBrowser('browserWarning')!='seen' ){

}

Inside the if statement we are going to pre-pend our warning box to the top of our page and set some CSS for it.

$("
You are using an unsupported browser. Please switch to FireFox, Opera, Safari or Internet Explorer 7. Thanks!   [close]
") .css({ backgroundColor: '#fcfdde', 'width': '100%', 'border-top': 'solid 1px #000', 'border-bottom': 'solid 1px #000', 'text-align': 'center', padding:'5px 0px 5px 0px' }) .prependTo("body");

Just one step left. We need to set up our onClick function for our close button. So with the jQuery click function we tell our button to Set our cookie and then hide the warning box.

$('#warningClose').click(function(){
	setBadBrowser('browserWarning','seen');
	$('#browserWarning').slideUp('slow');
	return false;
});

That pretty much covers the whole setup. Feel free to modify this in any way you see fit.

Source Demo (Firefox is also unsupported for the Demo)

Use jQuery with Google Analytics to Track Clicks on Outgoing Links From Your Site.

So you have a nice site or blog with lots of links to other places. Wouldn’t it be nice to use the power built into Google Analytics to track those links, without having to add the necessary JavaScript to every link? Here is a very easy way: Add outbound link tracking to a new or existing site. Provided that your links to other sites have the REL attribute set, you can track them very easily with some help from jQuery.

1. Download jQuery and install Goolge Analytics.

Go to jQuery.com and get the latest version. Then add the script include into the header of your site.

Now go to Google Analytics. Set up an account and follow the directions to get tracking running. Go ahead, do it now, I’ll wait. You should now have some script on your site that looks like:

var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js'
type='text/javascript'%3E%3C/script%3E"));

var pageTracker = _gat._getTracker("YOUR ACCOUNT NUMBER HERE"); pageTracker._trackPageview();

2. Add the jQuery to start tracking links.

In the head section of your page, you will need to add a few lines of JavaScript. You will need to setup the jQuery .ready function and add the code to that.

$(document).ready(function(){

});

Next use a jQuery selector to select all a tags on the page with a rel=”external”. To do this, pass jQuery the a tag element with the attribute selector option.

$("a[rel*='external']")

with this we add a click function to our jQuery object.

$("a[rel*='external']").click(function(){

});

With the last part we put in the function call to the Google Analytics code and we pass it the href that our a tag is pointing to.

pageTracker._trackPageview('/outgoing/'+ $(this).attr('href'));

This code makes the call to Google Analytics and passes a page path of “/outgoing/” and the url of where the click was headed. In your Google Analytics under content, you will see pages that start with “/outgoing/”. These are clicks that took people off your site. See below for how it looks in Google Analytics.

Adding Twitter to Your Web Site with JavaScript

Today at work we needed to pull our Twitter feed into our site. Not wanting to have to deal with the Twitter feed in back-end code, we decided to try out some already-written JavaScript setups for doing what we needed.

After testing out a few different ones, we finally settled on twitter.js written by Remy Sharp.

Twitter.js seems to have the most flexibility and had the options we were looking for. It also seems to load a lot more consistently than the others (although I think that is more of a network issue at work). Below is a list of all the ones we tried–they were all great. If you are looking to add your Tweets to you web site, below are some great places to start.

  • Twitter.js by Remy Sharp. Features a simple, clean setup that is easy to use and has a lot of options that can be set.
  • Tweet! by seaofclouds. This is a Jquery plugin and seemed to work very well. It didn’t do exactly what we were looking for, but since this is a Jquery plugin, it was hard to pass up.
  • addTweets This is great if you just lwant to add Tweets to you site with no work. You enter your Twitter info and addTweets generates all the code for you. You have up to 10 Tweets on your page with just a copy and a paste.