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.

Where to Start with jQuery Selectors

With jQuery there are many ways to select elements. We are going to cover two of the most popular selectors id and class.

jQuery uses the same selectors as CSS. This makes it very easy to select the elements you want to work with. The two most commonly used selectors are id and class. So before we start make sure you have your jQuery setup and the $(document).ready() function on the page.

Selecting by ID

This is best used when you want to target one specific element. The selector is exactly the same as what you would use to set styles for the particular element in CSS.

Selecting element with CSS and setting some styles.

#youridhere {
	display: none;
}

Now selecting the same element with jQuery and adding CSS styles.

$("#youridhere").css("display","none");

Selecting by Class

With the class selector you can select multiple elements at once. jQuery deals with multiple elements in a very simple manor. It returns an array of jQuery objects. With the way jQuery is designed it will automaticaly apply anything you do to your selection to all elements without having to loop threw the results.

Lets take a simples example of hiding all elements with a class of hide. To do this with CSS we would create the class in our style sheet like so:

.hide {
	display: none;
}

To do this same thing to all the elements with the class of hide in jQuery. You would use the following statement:

$(".hide").css("display","none");

This should get you started on the path of using jQuery in your projects. To read more about the selectors your can use in jQuery check out the documentation.

jQuery's document.ready(), What is it and Why is it Useful?

The document.ready() function is the first thing anyone should learn about jQuery. This function will allow you to take all that ugly behavioral javascript out of your markup.

Lets face it, nobody likes all those javascript:void(0); in the anchors href. As for that body “onload” function call, can that too, its no good. All that ugly code in the markup is just plain bad news.

With jQuery and document.ready() you can put all your event driven javascript in one file, making it easy to maintain and upgrade later. The document.ready() function works just as the name implies. Document refers to the DOM, or Document Object Model, while in this case “ready” refers to when the DOM is registered by the browser.

Before we start, make sure you have jQuery included on your page. For a quick refresh on how that’s done, click here.

Using the document.ready() function is really easy. Check out this example:

	$(document).ready(function(){
		//insert code here
		alert("this will flre when the DOM is loaded.");
	});

As with most code, there is a shorthand version of the document.ready() function. In jQuery, any function passed to the jQuery object will be bound to the document.ready() function, as seen below.

	$(function(){
		//insert code here
		alert("this will work the same as the code above.");
	});

This is how you would add a click event to all the anchor tags on your page using the document.ready() function.

	$(document).ready(function(){
		$('a').click(function(){
			alert("you clicked me!");
		});
	});

That’s all there is to it. Are you having an issue with jQuery, or any code you need some help on? Have an idea for an article you’d like to see? Feel free to leave a comment with any questions or suggestions.

Adding Twitter to your site with jQuery Part 2

This series of articles will explain how to retrieve information from Twitter using their API, and ways you can display it on your website in an attractive way. In Part 2 we will add some simple CSS to the tweet to make it look nice, and display all the data the twitter API returns.

As a special bonus for all four of you who will read this post, i’ve also built this into a jQuery plugin. First we will start by changing what we did in the last post a bit by creating a unordered list to hold the tweets.

	var $tweetContainer = $(document.createElement("ul"))
                                         .attr("id","tweet-cont")
       					.addClass("tweet-cont");
	base.$el.append($tweetContainer);

We will use each list item to hold the tweet data. I added an if statement that will add a class to easily style even and odd tweets, and then we add the code to include the users Twitter avatar and the tweet text.

	var tweetClass = "odd";
	if(i%2 == 0){
		tweetClass = "even";
	}

     var $tweet = $(document.createElement("li"))
                  .attr("id","tweet_"+tweets[i].id)
                  .addClass(tweetClass)
                  .addClass("tweet");
     $tweetContainer.append($tweet);

     var $tweetPhoto = $(document.createElement("img"))
                  	 	.addClass("avatar")
                  	 	.attr("src",tweets[i].profile_image_url);
     $tweet.append($tweetPhoto);

     var $tweetDesc = $(document.createElement("div"))
                  	 	.addClass("text")
                  	 	.html(""+tweets[i].from_user+": " + base.replaceURLs(tweets[i].text));
     $tweet.append($tweetDesc);

You’ll notice there’s a function in there called replaceURLs:

	base.replaceURLs = function(text){
		text = text.replace(base.options.aTagRegexp,"$1");
		text = text.replace(base.options.userRegexp,"$1@$2");
		text = text.replace(base.options.hashtagRegexp,"$1#$2");
		return text;
	}

This function will search through the text of the tweet and take urls and make them clickable, as well as finding twitter users and hash tags and linking those correctly as well.

Now we need to display when the tweet was created. That should be too bad right, we just create an element and use it to display the date. Normally when working with dates i’d say that was OK, except twitter is all about instant gratification. We want to know what’s happening and how long ago it was when it happened. Its for this reason we need a little extra code so we can display when a tweet was created in relation to the current time.

First we need to get some values to compare the tweets created date against:

	var minDiff = Math.ceil((today.getTime()-tweetDate.getTime())/(60*1000));
	var hourDiff = Math.ceil((today.getTime()-tweetDate.getTime())/(60*60*1000));
    	var dayDiff = Math.ceil((today.getTime()-tweetDate.getTime())/(24*60*60*1000));

Then all we need to do is write our compare logic. The seconds and minutes are obvious choices, but choosing when to stop displaying a message like “2 days ago” vs displaying the tweet date is up to you. For the plugin I went with 5 days. We will also be providing a link to the app used to post the tweet, very helpful considering there are about 800,000 different apps out there.

	if(minDiff < 59){
		timeDiff = "
about "+minDiff+" minutes ago from "+base.fixEncHTML(tweets[i].source)+"
"; }else if(hourDiff < 24){ timeDiff = "
about "+hourDiff+" hours ago from "+base.fixEncHTML(tweets[i].source)+"
"; }else if(dayDiff < 5){ timeDiff = "
"+dayDiff+" days ago from "+base.fixEncHTML(tweets[i].source)+"
"; }else{ var AMPM = "PM"; var myHours; if(tweetDate.getHours() < 12){ AMPM = "AM"; if(tweetDate.getHours() == 0){ myHours = "12"; }else{ myHours = tweetDate.getHours(); } }else{ myHours = tweetDate.getHours()-12; } var myDate = tweetDate.getDate() +"th"; if(tweetDate.getDate() == 1 || tweetDate.getDate() == 21 || tweetDate.getDate() == 31){ myDate = tweetDate.getDate() +"st"; }else if(tweetDate.getDate() == 2 || tweetDate.getDate() == 22){ myDate = tweetDate.getDate() +"nd"; }else if(tweetDate.getDate() == 3 || tweetDate.getDate() == 23){ myDate = tweetDate.getDate() +"rd"; } timeDiff = "
"+myHours+":"+tweetDate.getMinutes()+" "+AMPM+" "+base.months[tweetDate.getMonth()]+" "+myDate+" from "+base.fixEncHTML(tweets[i].source)+"
"; }

Finally, we can add a couple useful links that will help users view and reply to the tweets:

	var $tweetLinks = $(document.createElement("div"))
					.addClass("links")
                  	 	.html("Reply · View Tweet");

	$tweet.append($tweetLinks);

Thats all it takes to write out a tweet, al this code will get you something that looks like this (i know, the colors are awful):

tweets example.png

That was a bunch of code. I hope you enjoyed this series of posts, and I promise if I ever do a series of posts again i’ll write them all first before posting :-)

Check out this quick demo and of course, the plugin source code.

jQuery 101: Adding jQuery to Your Website

Everyone has to start somewhere. So lets get you setup to begin learning jQuery. The first thing you will need to do is get jQuery setup and running on your site. Now let’s get started.

The traditional jQuery Setup

1. Download the files

Make a trip over to the jQuery site and download the latest version or follow this link to the download page. You will want to grab the minified version of the code to save on bandwidth.

2. Add the script to your site

In the root folder of your site make a new folder called js. Then add the freshly downloaded jQuery script file to this folder. With the files in place you will need to add the script to your pages.

Open up one of you pages on your site and make you way to the head section of the page. Now copy the script tag below and paste in the head area of your files.


Once your script tag is in place you are ready to start using jQuery.

Using hosted files from Google

Google offers a great service. They host several of the most popular javascript library’s. This works well for sites that want to save on bandwidth or always have to latest code. Google offers several different ways to link to the script files. We are just going to use the direct link method. For more on the options of linking to these files check out the Google AJAX Libraries API.

1. Choose your version

There are a few options you have for choosing what version of jQuery you would like to link to. You can link to the main version of 1. This will keep your code updated to any subversions of 1. You could link to 1.3 this would keep your site running on the latest subversion of 1.3. Lastly you can link directly to the version you want to use.

Link to current subversion of version 1

http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js

Link to current subversion of version 1.3

http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js

Link to current version 1.3.2

http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js

Link to older version 1.3.1

http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js

2. Add the script to your site

I recommend you link to the current version that you know works with all of your code. So below is the script tag that you can place in the head section of your site. The script tag loads the current version as of this posting jQuery 1.3.2.


This will get you started on your path to learning jQuery. Look for more jQuery basics to come and also check out some of the resources listed below.

Harness the Power of the WordPress Post Class Function and Style Those Sticky Posts

The sticky post functionality in WordPress uses the post class function introduced in WordPress 2.7 to style your sticky post with css. In order to have your sticky posts styled different than your regular posts, you need to have the post class function in your theme within the post loop.

What is a sticky post and why would I use it?

A sticky post is a post that is plucked out from its publish date and moved to the front of your blog. This will keep the post on your homepage so you can increase the visibility of that post. Sticky posts have many uses–one would be if you were having a giveaway. You could stick that post to your homepage so everyone would see it when they visit your blog. Then, once the contest is over, you remove the sticky post option and the post falls back in line to when it was published.

Adding the post class function to your theme

Within the post loop there should be some code that looks something like what is below:

Rest of loop here

Now some themes use more than one class to style their posts. You could have a setup like the following where you have not only a post class but also a box class. Thankfully for you they have made it very easy to add that class into the post_class function.

Rest of loop here

To update the theme all we need to do is replace class=”post” with our function call. Your updated post loop will now look like.

> Rest of loop here

If you need that extra class like the second example that also uses the box class. All you need to do is pass that class name into the post class function.

> Rest of loop here

That is it for updating the code within your theme.

Adding style to your sticky post

The post class function will automatically add a class of sticky to any post marked as such in the post admin screen. So in your style sheet you will need to add some styles for this new class. Here we just added a different background color to our sticky posts.

.sticky{
	background-color: #c2c2c2;
}

Marking a post as sticky

stick-post-edit-window.png

In WordPress 2.8, make your way to the edit screen for the post you would like to make sticky. You’ll then see a box like the one to the left with the visibilty section closed. Click the edit link and you will now see the checkbox. That’s all it takes to take advantage of sticky posts in WordPress.

Be sure to check out the WordPress Codex to find more info on all the functions available in WordPress.

8 Must-Have WordPress Plugins to Improve SEO, Speed, and Security

Plugins are one of the things that make WordPress great. You can easily extend the functionality of WordPress without having to know much about PHP.

These “Must-Have” plugins are ones that I find myself using over and over again. The base installation of WordPress is an impressive piece of software and with these plugins, you can take it to the next level. Get your WordPress site running faster, backed up, secure, and search engine optimized with these 8 plugins in minutes. Just a little effort on your part to set up these plugins will go along way to improving your blog’s traffic.

All-in-One SEO Pack

Whether or not you are an SEO expert, this is a simple-to-use plugin. The All-in-One SEO Pack plugin optimizes your WordPress blog to help you get the most out of your content.

DB Backup

Download or email your backup with ease. You can backup and restore almost anything stored in your WordPress database.

Google Analyticator

With the ability to add your Google Analytics stats right to your WordPress Dashboard, this plugin is an easy way to track and view all those stats you like to see.

Google XML Sitemaps

It doesn’t get much easier than this to help Google and other search engines find all of your content. Simply install this plugin and generator your XML-sitemap. The plugin will generate a new sitemap every time you add new content.

WP-PageNavi

Add more advanced paging to your WordPress blog without having to know PHP.

WP Security Scan

Scans your WordPress installation for security risks and makes recommendations on how to fix them.

WP Super Cache

Speed kills–well, a lack of speed does anyway. This plugin generates static html files of your WordPress pages and can greatly improve load times.

Yet Another Related Posts Plugin

Helping you increase those page views. This plugin gives you the ability to show your readers related content on your site.

Something I missed? Let me know–I am always on the lookout for a good plugin.

Adding Twitter to your site with jQuery Part 1

This series of articles will explain how to retrieve information from Twitter using their API, and ways you can display it on your website in an attractive way. Part one we will go over the basic of the Twitter API and look at some simple code that will print out a list of tweets.

For this example I will use my own tweets, feel free to follow me @jaredharbour.

What is Twitter?

In recent years, social media has become a huge part of peoples lives. Sites like MySpace, Facebook and LinkedIn (which I sometimes refer to as ‘The Big Three’) allow people from all over the world connect and share their lives and ideas instantly. Recently Twitter has become the next big addition to the global conversation. Twitter is unique among the others in that its only function is to accept and display 140 character “micro-blogs”. Let me get one thing out of the way before we continue, micro-blogging doesn’t mean every message has to be about taking out the trash and mowing the lawn. There are 5 million+ Twitter users in the world today, and that number will only get bigger. Now lets get into some code.

The Twitter API

The Twitter API attempts to conform to the principals of Representational State Transfer or REST. I’ll leave it to you to read up on what that means, simply put it means that with the Twitter API you simply need to change the extension to get your results in a different format.

http://search.twitter.com/search.format

Since we just want to print out a list of tweets, we will start by using the search function. The search function will return its results in two formats, XML and JSON. We will use JSON because in my experience it’s faster and easier to use than XML.

http://search.twitter.com/search.json

For a more in depth look at the search function take a look at the Twitter documentation. Now lets get to the jQuery part. We get to use one of my favorite methods jQuery gives us, jquery.getJSON. This handy function will return the JSON via a GET HTTP request, just what the doctor ordered.

$.getJSON(
    'http://search.twitter.com/search.json?callback=?&rpp=25&q=from:jaredharbour',
    function(data) {
        // our code to handle the data here
    }
);

That’s not all though, we need to get at our data. jQuery makes it easy with the each function. This will let us loop through the JSON object with ease. In this case, “tweets” becomes our array of data. Then we need to check a few things to make sure we are in the section of the object we want. This logic isn’t perfect, but it will work for all the major browsers. The first and second if statements are to check if there are tweets to look at. I needed them both because it seems IE was unhappy with accessing the first element, because in some cases there isn’t one. The third if statement makes sure that what we’re looking at is in fact a tweet, and not some random piece of data.

$.each(data, function(i, tweets){
	if (tweets.length != undefined){
		if (tweets[0] != undefined){
			if (tweets[0].created_at != undefined){

			}
		}
	}
});

Now we just need to print out some data. Just a simple for loop and a document.write and we’re all set.

for(var i = 0; i < tweets.length; i++){
    document.write("
"+tweets[i].text+"
"); }

That’s all there is to it! In the next post I will get into formatting the tweets to add more functionality. Here are some of the topics I will cover later in the series.

  • Hyperlinking hash tags and users
  • Formatting tweet time and date
  • Linking to the Twitter app

Have a question? Looking for something specific? Leave a comment and I’ll get back to you!

We're attending the jQuery Conference!

That’s Right! We are signed up to join 298 other web professionals in Cambridge for this years jQuery Conference. The conference will be held September 12th and 13th at Microsoft New England Research and Development Center in Boston, MA.

We are really excited. We are waiting to see what topics are going to be covered, but we know there will be a 3 hour seminar for jQuery beginners that at least one of us will check out. We are also looking forward to meeting other people in the area who use jQuery, maybe exchange some ideas about jQuery or even the web in general.

If you want some information about this years jQuery conference, check out some of the links i’ve listed below. Also check back here for more updates, as we will be posting any new information when we get it. We will also be posting our live feedback while at the conference via Twitter. Follow @think2loud for all the updates.

UPDATE!

Keep up with the details of the jQuery Conference here. Only a month to go!

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