Archive

Archive for the ‘JQuery’ Category

Enhanced Visitor Event Tracking With Google Analytics and JQuery

February 16th, 2010 Rob 7 comments

Google Analytics has fast become the industry standard to track a plethora of web based information about your website. Whilst being totally free and easy to setup, you are limited to tracking elements that physically render in the browser – so items such as PDF, ZIP and RSS feeds links are not tracked, this because Google Analytics has a great reliance upon JavaScript. However, tracking such links can be achieved with a small amount of extra work.

Personally, I wasn’t aware you could track specific links with Analytics and only ever considored this when a client asked ‘why doesn’t Google show me the numbers of times my marketing report (read: a PDF file) has been clicked?’ – a totally valid request that I wanted to investigate.

Use JQuery to improve Google Analytics and track downloads, RSS, Email & external links

First things first, make sure you have a google Analytics account, the latest version of JQuery and the latest version of the analytics code running on your website :)

As with the majority of the JQuery magic, everything happens within the doc ready event listener – this will used to capture various clicks to select elements.

Tracking Download Link Clicks (PDF, ZIPs etc.)

$(document).ready(function() {

	$("a[rel=download]").click( function() {
		var fileName = $(this).attr("href");
		pageTracker._trackPageview(fileName);
		return true;
	});

});

Then on every link you wish to track, simply add the rel attribute to your non HTML files as follows:

<a href="myData.zip" rel="download">Download My ZIP Data File</a>

Tracking Downloads of Specifc File Types (E.g. PDF files)

Using the dollar sign to match against links that end in .pdf (or any extension you wish to track).

$(document).ready(function() {

	$("a[href$=pdf]").click( function() {
		var myPDF = "/pdfDownloads/" . $(this).attr("href");
		pageTracker._trackPageview(myPDF);
		return true;
	});

});

The /pdfDownloads/ is used to identify and seperate report data within Google Analytics.

Tracking the click of a specific link such as an RSS feed

Simply add an identifier to your RSS feed link (in this example the link was given an id of ‘rssFeed’):

$(document).ready(function() {

	$("a#rssFeed").click( function() {
		pageTracker._trackEvent("RSS", "RSS Subscriber Link Clicked");
		return true;
	});

});

Tracking mailto: Link Clicks

$(document).ready(function() {

	$("a[href^=mailto:]").click( function() {
		pageTracker._trackEvent("Mail", "User clicked on mailto link");
		return true;
	});

});

Tidying up….

You should also disable the clicked element to prevent multiple event recording and provide feedback. To do this, simple add the following at the start of each piece of code – disbabling the element and changing the cursor to an egg timer (although you could display a small graphic to make things look prettier):

$(this).css("cursor", "wait");
$(this).attr("disabled", true);
Categories: JQuery, SEO, google analytics Tags:

Getting Multiple Array Form Values With PHP

August 18th, 2009 Rob 3 comments
php array code

PHP Arrays

Further to my article on using JQuery to dynamically append form elements, I have come across situations where multiple items should be appended to the form each time, as opposed to a single input in my article (I did this simplicity). For example, at work I’m currently working on an internal system whereby a user needs to add an unlimited amount of client contacts for a client. Pressing the ‘add contact’ link will append 3 fields – one for conatct name, contact telephone and contact email. Each of these fields are named exactly the same way as before (using square brackets at the end of the name E.g. ‘name[]‘) and appended the same way using JQuery.

There are lots of articles floating about explaing how to add fields, but I’ve not yet seen anything explaining how to retreive multiple elements like this.

The only differnce arises when retreiving these multiple values from the PHP’s POST array. In the example I have appended 3 inputs, named cname[], cemail[] and ctel[]. The values of each can be retreived using a slightly enchanced for loop:

if (isset($_POST['cname'])) {
for ( $i=0;$i<count($_POST['cname']);$i++) {
$contactname = $_POST['cname'][$i];
$conatctemail = $_POST['cemail'][$i];
$contacttel = $_POST['ctel'][$i];
}
}

That’s really all there is to it and I’m finding that the latter comes in useful quit regularly in every day projects.

Reasons to let Google Host your JQuery Files

August 10th, 2009 Rob No comments

It’s often the case that I see busy sites hosting copies of the JQuery library locally. E.g

<script src="/js/jQuery.min.js" type="text/javascript"></script>

The preferred and better way is to host your JQuery through Google E.g.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>

So, why is this better? Well there are several valid reasons:

CDN (Content Delivery Network) – Google’s datacenters are located over a range of locations and when a user requests content the closest location is automatically chosen. This is better because it does not force users to download from a single server location (E.g your server) and the chances are Google will be able to serve content faster than your webhost. A similar theory is used for the popularweb based game called quakelive. Usually CDN’s are a service you pay for, but you’re getting this free through Google!

Less server load – When all your website’s files are located on a single server, downloading them simulainiously increases server load and some users will recieve delays while files download. By having an external location for your JQuery library the latter is not an issue.

Improved caching – This is the biggest benefit as users will not have to re-download content. Hosting JQuery on your own server will cause a first time visitor to download the whole file, even if they have several copies of the same file from other sites. Through Google’s CDN, re-requests for the same file will result in a response to cache the file for up to one year, as it understands that it is a repeat request for a duplicate file.

Local Bandwidth savings – by letting Google host the file for you, you are in essence saving bandwidth. For personal sites this may not be an issue, but busy sites will notice significant bandwidth savings.

Google actually suggests using a .load() function to load the library (see below), but this not only interrupts JQuery’s killer feature (document.ready), but also causes an extra HTTP request. Personally I prfer the old fashioned script method, even though there are several other valid reasons to use the .load() method.

<script type="text/javascript"
        src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
  google.load("jquery", "1.3.2");
  google.setOnLoadCallback(function() {
  });
</script>
Categories: General, JQuery Tags: , ,

Adding Unlimited Form Fields With JQuery and Saving to a Database

July 25th, 2009 Rob 21 comments

In this article I’ll discuss how to add an unlimited number of additional form elements to a form and then save to a database. The latter part is the key here as a variety of tutorials exist on adding form elements, but I have yet to see anywhere that actually explains how to manipulate these added form fields. For example, how to get values to store them in a MySQL datbase. In the example we’ll have a simple user signup form where the user can add multiple fields to describe their favourite websites.  The basic Form HTML is as follows (nothing amazing, just a simple html form):

<script src="js/jquery.js" type="text/javascript"></script>
<h1>New User Signup</h1>
<form action="index.php" method="post">

  <label for="name">Username:</label>
  <input id="name" name="name" type="text" />
  <label for="name">Password:</label>
  <input id="password" name="password" type="text" />

   <div id="container">
      <a href="#"><span>» Add your favourite links.....</span></a>
   </div>

   <input id="go" class="btn" name="btnSubmit" type="submit" value="Signup" />
</form>

The only part that isn’t standard is highlighted above. This is simply the link users click to add additional form fields on the fly. To make that happen we’ll need some JQuery:

var count = 0;
$(function(){
	$('p#add_field').click(function(){
		count += 1;
		$('#container').append('<strong>Link #' + count + '</strong>'+ '<input id="field_' + count + '" name="fields[]' + '" type="text" />' );
	});
});

» Read more…

Simple Ajax Content Loading With JQuery

July 19th, 2009 Rob No comments
JQuery.com Logo

JQuery - JavaScript Framework

Occasionally it is useful to silently load content into an area on a webpage. For example, you may have a list of recent comments that you want to refresh every minute. Using a meta refresh is one option, but this would cause the whole page to refresh, which could annoy the user. The solution is Ajax, where I’ll reload the content silently without a single page refresh. Even writing the simplist of Ajax functions is quite painful and requires a fair few lines of code to get things done. To make things simpler we’ll use my favourite JavaScript Framework,  JQuery.

The plan is to have dynamic content loaded via Ajax and refresh every x seconds. We’ll also have a loading image to show the user something is actually happening behind the scenes, as having nothing while the content is loading could make the user leave. The latter is especially important when querying large sets of data, where a delay is possible. You can get your own loading images from the ajax loading image site.Now we have a plan, we’ll get right into it.

First course of action is to setup our basic html page. It’s nothing amazing, simply a centered divider with a seperate divider for the loading graphic. Here’s the code we’ll be using (for simplicity I’ve used the style tag for the css, as opposed to having a seperate css file:

» Read more…

<