Working With Cookies In Javascript

Cookies are variables of temporary data which is stored on the visitors computers. They are normally used for things like remember my username on a login form. This can be a useful way to store information about your returned visitors without them having to log in to store information on a database.

It's worth noting that cookies should not be used to store secure information as they are just files stored on your visitors computer.

You can set a cookie on both the server side and the client side in this article we are going to look at the process you would set-up a cookie on the client side using Javascript.

Raw Javascript

Working with cookies in Javascript is not the best feature of Javascript, there is no easy way of dealing with setting and getting cookies.

All Values

To get all the cookies which are set for the current document you need to use the following.

var allCookies = document.cookie;

Setting Values In Javascript

To set a cookie you need to use the Javascript variable document.cookie, to add values to this you need to setup the data as a query string and add onto the end of the document.cookie.

document.cookie = "website=paulund";
// cookie is website=paulund

If you want to add extra data to the cookie then you just need to repeat the above step.

document.cookie = "secondwebsite=paulund-demo";
// cookie is website=paulund;secondwebsite=paulund-demo;

Now this seems easy to set data but this will not deal with expiring the cookie or domain for the cookie.

To set the expiry of the cookie you need to add the expiry on the end of the document.cookie.

document.cookie += "; expires="+date.toGMTString();

To set the domain path of the cookie you then need to set the path on the end of the document.cookie.

document.cookie += "; path=/";

With these factors you can add to just setting data on the cookie it can be difficult to handle you need to write a function to handle the setting of the cookie.

function setCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

Getting Values

As you can see there is a lot you need to do to set the values on the document.cookie but you will need to do even more to get values out of the document.cookie.

If you want to get a certain value you have set you can't just call the key of the data to get the value you have to use a function which will do a reg ex search to get the value of a key.

function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

Easier Way Of Working With Cookies In Javascript

There must be an easier way of handling the cookie data then having to create you own functions to deal with the different scenarios of setting, getting, all cookies, remove cookies, empty all cookies, testing if cookies are enabled.

There is an easier way of working with cookies there is a Github project called cookie.js, this is a simple javascript file which when included on your web page you can easily handle the cookie data.

Cookie.js

To use cookie.js all you have to do is download it from Github and include it on your page, download it from here.

Cookie.js

Then you can include it on the page by doing using the following code.

<script src="cookie.min.js"></script>

When this file is included there will be a new cookie object to use to set and get the data.

Setting Cookie

To set a cookie with cookie.js all you have to do is use the method set().

cookie.set( 'key', 'value' );

If you want to add extra parameters to the cookie you can set these up as the third argument on the method.

cookie.set( 'key' , 'value', {
   expires: 7,
   domain: "paulund.co.uk",
   path: "/",
   secure: false
});

Getting Cookie

To get the values from the cookie it is as easy as using the get() method, this will return string of the value of the key.

cookie.get( 'key1' );

Or you can even use a shorthand version of this by just doing.

cookie( 'key1' );

Get All Cookies

To get all the cookies available it is very simple by using the all() method.

var allCookies = cookie.all();

Removing Cookies

It is also easy to remove the cookies by referring to the key you have setup on the cookie, by using the remove() method.

cookie.remove( 'key1' );

You can even remove all cookies available on the domain by using the empty method.

cookie.empty();

Cookies Enabled

Visitors can turn cookies off on the browser so you will not be able to store data on the visitors computer, for this reason you will need to check if cookies are enabled before you try setting up new cookies.

With cookie.js you can do this easily by using the enabled() method.

if (cookie.enabled()) {
   // Cookies are on you can setup cookies
} else {
   // Cookies are turned off you can not use cookies
}

Cookie.js

As you can see using cookie.js is a much easier way to handle cookie data than using raw Javascript.

Download it from Github and use it on your next project.

Download Cookie.js

Use htaccess To Redirect Custom Error Pages

When your website server sends a HTTP error status code it will display some default pages which do not look good on your site and don't look professional.

The best solution to use if your server returns with an error is to display a custom error page with your own website skin.

There are different ways you can make the server display your custom error pages. You can either use your server side language to search for HTTP error codes before displaying a page and redirect the visitor to a custom page for that error.

An easier option is to use your htaccess file to redirect the visitor when it detects a server error code.

Use the following htaccess snippet to redirect visitors to custom error pages.
Continue reading »

Explaining The Different HTTP Status Codes

HTTP

When a URL is requested by the client to a server the server will return the resource and a HTTP Status code. The status code will let the client know different information about the request, if it was success, if it failed or if the resource has moved.

Here is a list of all the HTTP codes and what they mean.

  • 100's are informational codes
  • 200's are success codes
  • 300's are redirection codes
  • 400's are client error codes
  • 500's are server error codes

100 - Continue

This code means that the request header has been received and that the request body can continue to be sent.

101 - Switch protocols

This code means that the server has asked for the client to switch protocols.

102 - Processing

This code means that the server is processing the request from the client.
Continue reading »

Make Content Clickable In WordPress

WordPress has a great feature I've just discovered which allows you to convert plain text into links for URLs or email addresses.

If your content has URLs in the content but you haven't add the link you can use this WordPress function to convert all plain text URLs to be links.

The WordPress function you need to use is called make_clickable().

This accepts one parameter which should be a string of the text you want to convert.

It will be able to convert a number of different types of links:

  • URLs - Adds link to the URL
  • www - Adds link to the www link
  • FTP - Adds link to the ftp link
  • Email - Adds a link with a mailto around the email address

Continue reading »

Remove Default WordPress Image Sizes

When you upload an image to WordPress by default it will be converted to three different sizes.

  • Thumbnail
  • Medium Size
  • Large Size

If you don't want your users to use any of these images sizes on your theme then you might want to stop the user from using these different sizes.

You can remove these from being used by using the WordPress action intermediate_image_sizes_advanced and unset the thumbnail, medium and large sizes, this will mean the only size they have left is the full image size.
Continue reading »

Customizing WordPress Comments

Post comments are an important part of any blog, they give your readers a way of engaging with the author of the article. Comments are the main thing that makes a blog different to a normal website, websites will display information about a subject but don't normally allow readers to engage with the author. This doesn't give your readers a way to discuss any points the author makes in the article, this is where comments come in and are important for the growth of your blog.

Why Are They Important?

Comments allow your readers to provide their expertise to add additional points to the author article that they might of forgot. A good example of this is on this blog, here I blog about code snippets and web development tutorials. This type of blog it is so important to have comments as it means the readers can hopefully show me a better way to code what I'm trying to do.

Blogs are a two way conversion with the author and the reader I learn so much from the readers of Paulund and I hope they learn as much from my blog posts as I do.

Problems With WordPress Comments

Above I have spoke about the benefits of having blog comments turned on and this is a massive benefit which is why the majority of blogs have comments.

But with the benefit of comments there is also a lot of disadvantages of comments especially with WordPress.

Automated Comment Spam

This is main problem with WordPress comments and because WordPress is so popular it makes it an easy target for automated software crawling the web look for WordPress and comment on the posts.

By default WordPress allows any commenter to leave a comment with the following fields: Name, email, website and comment.

When these are displayed the website url will be made into a link around the commenter name making this an easy way to get links back to your website.

If you have a WordPress blog you will see that as soon as you start getting visitors to your blog you will see the comment spam. These are fake comments made by bots to try to get links back to their website through a link in the commenter name.

If you don't have a way of protecting your site against comments then you could quickly build up a list of fake comments on your blog, which doesn't make your site look professional. With the new Google updates your website will be penalised if you are linking to bad websites, this means you need to careful when linking to another website.

The best to protect your blog from comment spam is to install the WordPress plugin akismet.com/, this will check all your comments and see if it is a spam comment or not.

Manual Comment Spam

Akismet is a great plugin to protect your blog against automated spam but it can not protect against manual spam comments. These are humans which go on to your website and comment on as many posts as possible to get links back to their site. Most of these comments will be something along the lines of "nice post" or "great article" or "thanks for sharing".

One way of protecting against manual comment spam is to remove the link around the commenter name, if the commenter can see they don't get a link back most will not leave a comment. I tried this here on Paulund and the standard of intelligent comments has massively increased, now I know every comment is there to add value to the article.

You can remove the URL from the comment section by using the following snippet.

function remove_comment_url_fields($fields) {
    if(isset($fields['url']))
    {
         unset($fields['url']);
    }
    return $fields;
}
add_filter('comment_form_default_fields','remove_comment_url_fields');

Time For The Author

Another problem with comments, which is infact a good problem to have is too many comments. If your blog has too many comments you need to make the choice of moderating the comments or not. If you don't moderate the comments then you can find people take advantage of this and you get more manual spam comments.

But if you start to moderate the comments then you could find it takes up valuable time moderating the comments which could be spent creating more awesome content. You need to make a decision, are comments more important than spending more time on creating content. For some people they are more important but others would argue that they would prefer to spend more time on creating awesome content and allow people a different way to discuss the article.

Some of biggest blogs in the world that have turned off blog comments are:

Continue reading »

How To Remove WordPress Post Meta Boxes

On the WordPress post screen there are a number of meta boxes which give you options to attach to the post.

For example you can change:

  • Categories
  • Tags
  • Featured Images
  • Excerpt
  • Trackbacks
  • Custom Fields
  • Discussion
  • Slug
  • Author
  • Revisions

If you have a multiple authors on your blog then you might want to disable some of the post meta boxes to anyone other the administrator.

For example you wouldn't want a guest author to disallow the comments or trackbacks on the article, this should be up to the administrators of the site.

To remove a meta box there is a WordPress function remove_meta_box().
Continue reading »

Free Premium Files For July 2012

Each month the Envato marketplace brings you free premium standard files.

Envato is a web marketplace where you can get premium files for different areas of your website. My favourite marketplaces is the script marketplace CodeCanyon and the Blog theme marketplace ThemeForest.

Here are the files which you can get for free for July 2012.

King Button Maker CSS3

King Button Maker CSS3

69 purchases at the price of $5.

  • Easily to add Icon Character Icon
  • Animation with CSS3 Transition
  • Inner and outside Shadow available to customize
  • Gradient Color
  • realtime preview of Button
  • Rounded-Corner(only for browser that support webkit)
  • Document included

Get Your Free Copy
Continue reading »

What Does Your WordPress Theme Support?

By default your WordPress themes will support a number of features like these:

  • Custom headers
  • Custom Backgrounds
  • Post Thumbnails
  • Menus
  • Automatic Feed Links
  • Editor Style
  • Widgets

Before WordPress 3.4 you needed to register these different feature separately, but now with 3.4 with can use the WordPress function add_theme_support().

Business WordPress Theme - ThemeForest Previewer

Enable Custom Headers

Before WordPress 3.4 you needed to use the WordPress function add_custom_image_header().
Continue reading »