Posts by Rob Allport
Getting Multiple Array Form Values With PHP
12
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.
CSS Sprities and Website Optimization
1One of the latest and most well established design practices are CSS sprites. This is the practice of combing multiple images into a larger and single, composite image. By using the CSS background-position property selected portions of that master image (or sprite) are displayed. The main issue here is how can a larger image witha larger file size be beneficial, especially when compared to several smaller images? The answer lies in HTTP requests and Yahoo’s 80/20 rule explains this much better than I could! To summarise, the numbers of HTTP requests to the websites is drastically cut, thus loading the page much faster in single request. Another major beenfit is that not Javascript is required for mouseover code, so you can make image rollovers easily. I have used this technque in the past, but like a lot of people never knew it was called sprites.
In fact, using sprites are so effective many of the internets biggest site’s are using them, all in slightly different ways. On such sites a truely huge number of requests are saved every day. For example, Youtube, Google, AOL, Amazon and Apple all use CSS sprites. Take the mimilist example of Google (left):

Google CSS Sprite
Youtube, does things slightly different and uses a absolutely massive sprite 2800px in height! You’ll notice that some sprites are tightly packed together and other have spacing around each image. This is to allow for browser based text sizing, that would otherwise display multiple background images. A good example of planning for such an occurance is Digg’s sprite, where each image is highly spaced out.
The CSS is relatively simple. Take the example of a simple unordered list with a different image for each item. I made a very simple sprite and applied the background-position property to each link class. Here’s the simple HTML used for the list: (more…)
Reasons to let Google Host your JQuery Files
2It’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>
Fixing Common W3C Validation Errors and SEO
0Yet another thing to check when doing SEO is that your site validates via the w3c validation checker. A site that is xHTML valid will recieve more frequent search engine crawls and more importantly, longer crawl times. I won’t bore you with further details about why validation is a good thing (it’s a huge subject), but if you must there is a great article about the subject right here. Creating a site to an xHTML valid standard encourages better coding practice and more semantic coding – making your site easier to crawl. You are also giving your site a betttr chance of displaying the same across multiple and future browsers.
Another less known theory is that spiders get full when crawling a page, semantic coding practice will allow for cleaner and more lightweight code. For instance, when crawling a badly coded page with lots of line styles and JavaScript (E.g. content not useful to a spider) the spider may become full too quickly and leave – missing you important content contained further on within the page.
Validating your site to at least xHTML Transaitional 1.0 (the test strict version, compared to xHTMl 1.0 Strict) is highly encouraged and is an area often ignored by developers. Below, I’ll quickly outline some of the common validation errors and how to easily fix them:
cannot generate system identifier for general entity X - 99% of the time this relates to errors with entity references such as ampersands in URLs. E.g. having an url like product.php?id=2&mode=view would result in this error as the ‘&’ wasn;t used within the url.
required attribute “alt” not specified – simply find the line number and add an alt tag for the image. The presence of an alt tag is required for both transitional and strict doc types.
XML Parsing Error: Opening and ending tag mismatch – Depending on how organised you are when coding this fix can take a matter of seconds or a lot longer. It relates to unclosed block level tags, such as a table or div. One plus point is that fixing such an error often results in several validation errors being fixed at once.
Adding Unlimited Form Fields With JQuery and Saving to a Database
67In 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" />' );
});
});
Simple Ajax Content Loading With JQuery
0Occasionally 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:
301 Redirects for SEO Using htaccess
4
301 Redirects Prevent 404 Errors
Google treats www.website.com and website.com as two totally different websites. This is very bad for your (or even a client’s) website as it may lead to duplicate content and different pageranks to those sites. This is how Google “canonicalizes” the url and is very bad from an SEO standpoint.
In essence, a web server could return totally different results for each of those pages. I have also encountered the situation where clients have set their preferred domain in Google webmaster tools, have given out the opposite version for SEM and wonder why they don’t see results
You can easily check the above by using the “site:” operator in Google search. E.g. site:www.website.com and site:website.com
You can use “mod rewrite” rules as a powerful method for redirecting many URLs from one location to another. This is a simple server level technique for handling redirects. The way people handle this canonicalization issue is purely a personal choice, although the below method can be altered for directing to the none www version of the url.
The .htaccess file is simply an ASCII file created with any normal text editor. You need to save the file as ‘.htaccess’ (no filename, .htaccess is the extension!). Open you newly created .htaccess file in your favoured text editor and add the following lines of code, replacing domain.com with your domain:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^domain.com
RewriteRule (.*) http://www.domain.com/$1 [R=301,L]
Upload the .htaccess file to the root folder of your website and you’re done. All your traffic will be permanently redirected from a non-www version of your website to a www version of your website. To do the opposite (direct all traffic to the non www version use the below code in the .htaccess file):
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.domain.com
RewriteRule (.*) http://domain.com/$1 [R=301,L]
