Some tips to make a developer's life easier

Today I wanted to share some experience I gained building apps. It is not so much about writing code this time, more on best practices of development. I hope you enjoy it!

Developing is as nice and idyllic as long as it is on your localhost and you are the sole user. Once people start using it in the real world, complications start. And that is a good and enriching experience. You see, you aim for certain things, users might see it another way, they might have a totally different interpretation both of the message as well as the use (UX).

In this post some things I learned, sometimes the hard way, usually just by being open-minded, communicating with your users from the beginning.

I think the most you will learn by being open and honest towards your users and accept that they can see things in another perspective which sometimes is better, at other times you might better stick to your point. And dare to make mistakes, without mistakes you won't learn that much!

1. Design with the end-goal in mind

Nothing is so frustrating as wasting time implementing features that were never requested nor needed. The most important thing is to realize for who you are making your app, be it a complicated data mining app, a social app or just a simple inquiry form.

Communicate often, very often. You tend to have the goal in mind at the start, but what happens down the road? Developers take hundreds even thousands of decisions during the development of an app, lots are easy, others are crucial to the success of an app. There is so much to do that wasting time will harm other areas of the development cycle, like testing and refactoring code.

Accept changes, web development is a dynamic area and often requirements change as you go.

2. Stick to the bare minimum and expand from there

As many others I want it to look great, I incline towards a good design from the start. This is certainly an important aspect to attract users, give them a positive experience and keep myself motivated. However, the essential things go first. A form: does it work when a user enters x or z? Is the data I requested relevant to accomplish my goal? Redirection between URLs, authorization of users, etc. As nice as it looks, users want the app to work well!

I still do the functional and appearance stuff in parallel but it is best to be absolutely clear about the functionality of something before investing a lot of time in making it beautiful.

Closely related is focus. Coding, as writing, requires a lot of concentration. This is the first post I write outside of Wordpress, in a text editor, I love it! I am less distracted, writing goes faster! The layout for later! Work on the architecture of the house, then on the decoration.

3. Get feedback and get it soon!

Your mind carries your experience, your intuitions, your (!) assumptions. I kind of trust them most of the times, but we are all influenced by beliefs and experience. Initially this is a good thing, but it can create blind spots at the same time. The art of making good apps, is to be able to think as the user. This can be hard, because often we haven't ever met the end user nor do we know his/her motivation. So it is critical to get feedback as soon as you have something slightly decent to show them. I am sometimes surprised by the difference in vision and experience users come up with.

Typically I process feedback and go back again. Doing this over and over makes the product as close to the enduser as possible. It can be a patience battle but best is to take and process feedback early on, because if you wait too long it might take much more work to correct / improve things (if still possible). A diverse group of test users could be of essential value.

Once the tool is in the air, some monitoring tools should be used, like google analytics or a simple usage counter. You can define success rates for yourself. I usually do a feedback round after some time.

ACCEPT CHANGE, sometimes breaking with an existing plan is the best thing you could possibly do to improve your app. It might take some acceptance and effort though. ACCEPT PERMANENT CHANGE. Requirements and needs change. A website / web app is something dynamic, not static.

4. Test, test and test

One thing I'd like to learn is to build a test suite. This is also one of the reasons I want to learn more ruby on rails, the framework that has this deeply integrated. You can't test enough. Bugs will arise, it is natural to development.

Software development takes place in our heads, we take hundreds or thousands of decisions during the course, it is inherent to a developer to solve bugs. If you like living in a 'perfect' world where things go well, don't become a developer. Part of the developer's job is to troubleshoot problems, debug 'weird things' you didn't (probably couldn't) foresee. In the real world new variables are added to the mix, so try to be sure you have tested as much you possibly could in the 'controlled' environment to be able to face the challenges of the 'live' environment.

Again, I stress the value of test users. Don't be surprised you will make some important last-minute changes based on their experience.

5. Set expectations

It is easy for an enduser to think a new feature is just something you hack together in an afternoon. Sometimes this is true and it is a satisfying job for small apps. However, in a controlled environment, bringing changes into a live app with the risk of changing or injecting bad behavior in other variables, makes it not that simple.

Best thing is to add all bugs and RFEs together and work on them in batches. Then roll them out in releases. I read somewhere that Facebook rolls out code changes once per week but it really depends the product and environment you are working in.

6. ... and above all, just have fun!

Developing apps is a very exciting business. Seeing something coming alive from the ground up has something magical to it. Remember that if you are solving issues, as hard as they seem sometimes, you are actually growing in your craft!

Share the word or join..

Did you like this post? Tell your friends via the social media buttons on this site...

You can also join my Facebook group or get a weekly Mailchimp newsletter to keep up with my new blog posts. You can subscribe in the sidebar of this site ...

Let Facebook "Like" button pick the right image!

How common: you have 20 images on your site, you place a like button on your site. You see others start to "like" your content but with the wrong image. Actually, last year I heard the complaint more than once because Facebook started to add an image to a "liked" post. Luckily it is not hard to fix this ..

Why is this an issue?

As said, some time ago the Facebook "Like" button would just show a phrase in your profile "you liked blabla..", but now it shows the thumb and some text, typically the first paragraph of the article. This is seen on your profile and in your friend's news stream.

Example

I tested the like button on my site to see that it takes a random image, one of my social share buttons. Not quite what I want of course. Now it seems erroneously that the article is about digg :(

Compare this with "Facebook Share" where you can select the thumbnail you want to appear alongside the post:

Or better, control which image is visible !

The solution

Check out this interesting post.  Basically you can use the meta tag to tell which image to show on your post to your wall:

<meta property="og:image" content="<your image link>"/> 

Facebook's Like Button page explains the tag as:

og:image - The URL to an image that represents the entity. Images must be at least 50 pixels by 50 pixels. Square images work best, but you are allowed to use images up to three times as wide as they are tall.

So this is easy to implement. Just control the meta html tags. But what if you have your Wordpress blog and you don't want to poke to much in the code (for example, you are not using a child theme). I did some research and it depends the plugin you use. Sadly enough I could not find one plugin that would be that flexible to let me choose the image that would show up..

Wordpress

Up until now I used fbLikeButton, but it does not add any og:.. meta properties.
Update: Nustiu (comments) confirms FbLikeButton has indeed everything you need. He says that if you want one default picture or for every single post another picture, it does the job. He also pointed me to this tutorial. I am not sure if it is an improved version or I initially overlooked it. In latter case sorry, in both cases this might be interesting to try, so cheers Nustiu ! I personally stick with Michael Fields solution for now ( see later on in this post )
== end update ==

I did some searching and I found a better "Like" plugin that does the work, but still not to my satisfaction. The Like plugin has the exact same appearance and config settings (e.g. show the "like" button before and after the post), but it also adds the meta tags. The only problem is that you can only specify one image. So if you want all your articles to carry your logo, just specify the full URL to that image and you are done. For example:

<meta property="og:image" content="http://bobbelderbos.com/.. ..badge_bb.png" />
..

A better solution

If you have a child theme, you can place hooks to existing WP functionality. I found a brilliant blog post from Michael Fields where he explains how you can add the "Like button" to your posts and set the meta tags for each and every post. It sets the "featured image" as og:image, and it is that image that shows up in the Facebook post upon liking the URL.

For me this is the ideal solution, because I always make an image that characterizes the post and that will show on my homepage and in my blog's archive page.

Testing two posts it works great:

<meta property="og:image"
  content="http://bobbelderbos.com/ .. .. readitlater.png"/>

<meta property="og:image"
  content="http://bobbelderbos.com/.. .. fb_comments.png"/>

.. these are the featured images of the two posts.

It seems to work great:

So thanks Michael Fields for sharing this solution! I think a lot of us are looking for this ..

Outside WP, another option

When you don't use Wordpress, and you want user's to send your content to their walls, you can use the Facebook API to control how such a post will look like. I covered this technique here and use it for sharemovi.es and my reading list.

Debugging

Facebook's lint is a great tool to debug issues with Facebook's share plugins. When you put in an URL it shows how Facebook reads it. Note the <meta .. og: .. .. > stuff in the example below:

Organize your reading with Read It Later

With so much info these days, one needs to organize. That's where Read It Later comes into play: save what you want to read and have easy access to it, anytime and anywhere. Read your articles text-only and even offline. In this post "the app" to use to organize your reading.

To be in sync

Like Dropbox, Read It Later is a cloud service that is extremely useful to sync content across devices. Typically in the evening I go through my twitter and facebook streams, find some interesting articles, but I don't have time to read them.
So you are faced with a dilemma: shall I just ignore this stuff, "favorite" them in twitter (while this is improper use of "favorites"), bookmark the links to a service called delicious (while I am not sure the article deserves to be bookmarked), copy the URLs to a text file or email the link to myself (which is the worst option)?
For me none of these options were really even close to an ideal solution. So I created a new account at Read it Later and I have a feeling I read more because I bundle the blogs and articles together and read them at specific intervals.

Mobile device

After you have created your account, if you have a mobile device, you probably want to install the app on it as well. For example for the iPhone you can do this here. Additionally you can configure your browser and twitter to use Read It Later.

Firefox plugin

You can add Read It Later to Firefox from this page and from the URL bar you can easily add links to your list clicking the yellow "greater than" icon:

You can also use alt +W or right-click + "Read this page later". In the App settings in Firefox Addons, there is a wide range of settings, it's broader than I thought..

Twitter

Twitter for iphone lets you integrate you Read It Later account so that you can save links with one touch. Read It Later is integrated in lot of other apps. I find it particularly handy with Twitter where there is an infinity of articles. I typically scan the tweets and save some interesting articles for later reading. Read It Later is really helpful here.

Other advantages

-Read It Later has offline mode so no internet connection is required. You can download the articles when online and read them offline.

-Another great advantage is that you might have a better reading experience. With the text-only toggle you can read the article without distracting images and ads. It's similar to readability, another great app to help you "de-clutter" your reading.

-You can share to other networks, but you need the Pro version for that. I didn't try it so far.

-As shown above: lot of options and customizations. There is even an API to bring Read It Later to your own apps!

What about you?

Are you using Read It Later, or you prefer alternatives like Instapaper? If so, why?
Or do you use something that is even better?
Let me know ..

More info Read It Later

- read it later blog

- read it later Firefox Guide

- bookmarklets (use in Chrome)

- build your own apps

You like this post?

You can subscribe in the sidebar to get a weekly (Mailchimp) Newsletter with my new blog posts. You can also follow my blog at Facebook. Feel free to leave a comment or contact me.

Pros and Cons of the new Facebook Comments plugin

This week Facebook released a mayor upgrade to their existing Facebook Comments plugin. This plugin, part of Facebook's Social Plugins, lets visitors comment on your site's content. In this post some details about the upgrade and an issue I ran into when upgrading the plugin on one of my sites.

The intro video is quite cool, I suggest you check it out and read the instructions page and the post on the Developer Blog, if  you want to use this plugin.

What's so cool about this upgrade?

1. Most interesting comments first (friends and "most liked" comments first)

2. You can reply from the news feed which will be synced back to the comment box on your site. So this allows for easier interaction with your content's comments and potentially more traffic to your site.

3. When somebody replies to your comment you will be notified in Facebook

4. Admins have control via a whole new moderation dashboard which let you handle comments of all your FB apps. Also moderation has more options now.

5. Easy to upgrade the first version of the comment plug-in by adding migrated="1" in the fb:comment tag

What is less cool?

1. Privacy. One aspect that might disturb people is that Facebook shows more context about the person that places the comment, like country and work place. Of course this can be minimized by adjusting your privacy settings, but I can imagine that people might be surprised when they put their first comment on another site that uses the new version of the plugin.

2. Issues with the migrating and fql-ing all comments of an app .. see further down

3. Fixed width of 500px, if you use a smaller width, different text elements will overlap. I reserved 410px for the previous version so I had to tweak the CSS of my app to neatly fit in the 500px box. It could be that Facebook will address this in the future.

 

Code

As before, it's plain easy to deploy:

<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script>
<fb:comments href="YOUR_CANONICAL_URL"></fb:comments>

(with the migration="1" flag if you upgrade an existing code snippet)

 

Migration issues

On sharemovi.es I have comment box per movie url, so I had a serious challenge to check back and forth v1 and v2 of the plugin.

I had to skim through the comments on the developer blog to figger out that when you didn't use the XID flag in the first version of fb:comments , like :

<fb:comments xid="YOUR_XID" migrated="1"></fb:comments>

.. you wouldn't see your comments in the new version. Holy crap, all the movie comments were gone! In the end I got it fixed by urlencoding the URL. There was a bug in the code requiring you to urlencode the url twice. Facebook got this quickly fixed and the comments came back with the following snippet (pff.. )

<fb:comments migrated="1"
  xid="<?=urlencode("http://".$_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"])?>">
</fb:comments>

 

Querying comments with FQL

Another thing that got 'broke' was the listing of number of comments. A shame, because I was quite glad with my code that could extract the number of comments per movie URL. Clicking the number would get you an overlay with the comments, styled with my own CSS. So comment box generated content extracted to other parts of the site.

Unfortunately this doesn't work anymore

$fql = 'select xid,count from comments_info where app_id=<<my_app>>';
  $param  =   array(
  'method'     => 'fql.query',
  'query'     => $fql,
  'callback'    => '',
  'access_token' => $session['access_token']
);
$fqlResult = $facebook->api($param);

The newer method Facebook proposes would be something like the following, but I cannot get it to work for my URLs:

select post_id, fromid, time, text, post_fbid from comment where object_id in (select comments_fbid from link_stat where url="http://developers.facebook.com/blog/post/472")

I will be checking this further of course, when I have the solution I will post it here .. Of course if somebody reads this and has found the solution, please put a comment here with the solution :)

Number of comments

Just new in the FAQ of the comments plugin is the number of posts for a particular URL. Unfortunately it doesn't work for sharemovi.es but it is a cool new feature, and it seems Facebook replied very fast on requests from users here:

<fb:comments-count href=http://example.com/></fb:comments-count> awesome comments 

or

<iframe src="http://www.facebook.com/plugins/comments.php?href=example.com&permalink=1" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:130px; height:16px;" allowTransparency="true"></iframe> 

Examples new comment plugin

Currently I am using the comment box on my two Facebook Apps to let users comment on movies and books:

sharemovi.es (blog post: Sneak preview: sharemovies)

my reading list (blog post: Hi folks, what are you reading? Share it on “My Reading List”

Like this post?

Share it using the social media buttons at the top and bottom of this post. Or post a comment, I like to hear from you ..

Hi folks, what are you reading? Share it on "My Reading List"

Today I announce a new Facebook App I built: My Reading List. It allows you to keep a reading list and share interesting books with your friends. This app makes sharing your favorite books very simple. Just login with Facebook and you are good to go..

Technology and idea

The app uses the Facebook API to identify you. Secondly it uses the Google Book Search APIs to extract the book info like the title, a thumbnail and a link to more info provided by Google. I made a design of 540px wide so it can be used on my domain as well as in the Facebook Canvas. Like a site for movies, I always wanted to do something similar for books. Like movies, you get a lot of good tips from friends. I also like to share what I am reading and keep a simple list of it. More info about the Canvas can be found at the Facebook API documentation.

Trigger

Amazon has this great Reading List app. I stumbled upon a post where people asked why this wasn't ported to Facebook (and why various reading lists couldn't be synced to one reading app, which unfortunately is not possible for linkedin / amazon's reading list). The Facebook argument was already enough to get me going :)

Besides I like reading!

Few years ago I would "schedule a read" with a friend, we would plan to read a book together and discuss it. It was highly motivating and it led to good discussions and fun learning. Why not bring this kind of fun to the powerful APIs Facebook and Google have to offer?!

Design

Let's see what the My Reading List app looks like and what you can do with it ..
This is the homepage when logged in with Facebook. You need Facebook to add books and use other features:

Of course you can browse the published titles without a Facebook Login. Here is the "Logged out" view of the site:

Add a book

When you are logged in you will see an "Add" button, click on it and a form slides out to add a title:

And as you start typing the Google Book Search APIs shows you potential titles. It's a similar data mining exercise I did before with sharemovi.es. It uses Juery's autocomplete plugin and submits the form automatically when clicking on the book you want to add:

.. then, upon selecting the title you want to add, a form slides down to publish this title to the stream with your opinion about the title:

It gives you the option to say you want to read it, you are reading it or you have read it:

Moreover, it lets you post it to your wall, but you can always choose to only leave the info inside the app:

Once you click "Add Book" the book is published to the stream. If you choose to publish it to your wall, something like this appears on your Facebook Wall:

Search

You can search for books and readers. Each book has has its own page with the  enhanced Facebook Comment plugin and a neat overlay with a preview of the book (thanks to Google's Preview Wizard).

Checking out the Python title:

You see all the social features. Click on the Google Preview button and you can take a look inside the book:

** Keep in mind that if Google does not have a preview of the book available the Google Preview is not visible on the book's page. However, in the stream of books on the homepage, the same Google Button opens a new page (tab) with more details about the book. A request for enhancement would be to detect when there is no Google Preview when requested and also put the link there instead..


More stuff ..

Other features are displayed for each title on the homepage (when not drilled down to a specific title) - it consists of 3 actions:

1. Comment

With the comment button you will be taken to the book's individual page to comment using the Facebook Comments Plugin (see second printscreen under "Search").

2.Recommend

You can use the mail button to write a quick recommendation to friends. This works like this:

a. click on the email icon, a form pops up to write your message:

b. when you click on the "Next .." button you get the Facebook Requests dialog with the info copied in there. This second dialog is needed to select one or more friends to send the recommendation to:

c. Your selected friends will get a notification of the recommendation in Facebook:

d. When a friend clicks on it they will see the recommendation + the URL of the book title.
The "Accept" button of Facebook has no extra functionality yet, it just takes you to the app (Canvas version)

3. Like

Apart from the FB Like button plugin, I made an internal "Like" system.
Under the "Popular" button in the sub navigation bar, you can see which titles were liked this way:

.. when clicked:

Please try ..

I am looking forward for more users to get on-board! I would love to hear your thoughts and feedback!

It is an experiment, so don't expect it to be complete. For example edit/delete of existing data, "your reading profile", adding other reader's books to your list, etc. would take up too much time for this trial.

The app is hosted at my domain but can also be used from within Facebook and has the following Facebook page

Next ..

I think this covers about all features. In future blog post I will cover the technical aspects of these features. What plugins did I use? How can you use the Google Book Search APIs? More on the Facebook API (see "Further reading" at the end of this post). CSS tricks I became to like. And of course jQuery for enhancing the user's experience.

 

Other posts that might interest you ..

1. Sneak preview: sharemovies

2. Twitter API: tweet with PHP

3. Facebook API: post with PHP

4. How to build a movie trailer API using gData

5. My 5 favorite jQuery snippets

And above all ..

Happy reading!! Let me know what books you like ..

Great book about software engineering

Must read

I finally had a chance to finish reading The Pragmatic Programmer: From Journeyman to Master. Any software developer should check out this title. It's full of wisdom and philosophy behind the craft, it is brought in a humorous way full of entertaining anecdotes and interesting examples and analogies.

Good practices

This book is all about getting into the habit of writing maintainable code. It is full of good practices each software developer should benefit from: prevent software rot, the concept of DRY (don't repeat yourself), writing bullet-proof code. Avoid programming by coincidence, test ruthlessly, define requirements, automate processes and much more .. GUI/MS developers might find it Unix-biased, but I think they make a point about the power of the Command Line :)

Some examples of all this good stuff ..

Software Entropy:

The quality of your apps stands and falls with putting out each fire consistently, as soon as spotted. "Don't Live with Broken Windows" is a brilliant analogy.

Orthogonality

Decouple your software modules, let components be as independent as possible. The authors give a great example of a helicopter as a tremendous complex system where every change impacts all the other inputs. Minimize coupling in software creation.

Prototyping

We prototype "to analyze and expose risk, and to offer chances for correction at a greatly reduced cost". This might free you from potential perfectionism. Making a sketch or programming "disposable code" at the start of a project might be very useful to explore ideas and features.

Assertive Programming

The authors are very realistic here: "If It Can't Happen, Use Assertions to Ensure That It Won't" - we all have the tendency to think sometimes: "this could never happen". Well unless you know the future, it is very likely it could, so you should use assertions (exceptions) as they will be your friend when debugging your code.

Programming by Coincidence

The importance to know why something works or not. Again this is having the discipline to not reside in "It works now, better leave well enough alone....". What happens if the code is applied in another context? Can you really prove your assumptions?

Stone Soup and Boiled Frogs

The authors give a great metaphor to show the point of systems getting gradually out of hand:  ".. they say that if you take a frog and drop it into boiling water, it will jump straight back out again. However, if you place the frog in a pan of cold water, then gradually heat it, the frog won't notice the slow increase in temperature and will stay put until cooked.". The point is to always remember the Big Picture, we can easily get stuck in details if we are not 100% aware what we are doing

Further reading

I generally see the following books listed as "must-reads" for software development. Learning new languages and crafting in known ones, makes it hard to keep up. Personally I take some time every now and then to go back to the theory. Apart from practice, understanding the concepts helps a lot!

Design Patterns: Elements of Reusable Object-Oriented Software
Refactoring: Improving the Design of Existing Code
Code Complete: A Practical Handbook of Software Construction
Clean Code: A Handbook of Agile Software Craftsmanship
Patterns of Enterprise Application Architecture

Companion volume ..

McConnell's "Code Complete" is said to be a great companion to The Pragmatic Programmer. I bought a hard-copy few years back and I agree with this statement. I only read it partly until now but I have to say it is very interesting! It focuses more on the ins and outs of writing code so I wanted to learn some more c++/ java (compiled programming languages) before I dare a complete read. When I have read it, I will definitely dedicate a post to it :)

And what about you?

I assume most readers of my blog are active in software development.
- did you read The Pragmatic Programmer and if so, what is your opinion about it?
- what other books did inspire you to become a better coder?

My 5 favorite jQuery snippets

jQuery is a standard library I use to add user-rich experience to the websites I make. It is quite easy to learn and animations, Ajax and DOM manipulation are often quick and painless. There is also a lot of documentation + forum wisdom available. In this post you will see some nice effects at work. Before we start ..

Download the latest jQuery version

First off you need to load the base file before any of the following will work. At this time of writing you can get v1.4.4 from the jQuery website. This post will show the effects and globally explain how they work. For in-depth understanding of jQuery try one of these titles: jQuery in Action, 2nd Ed and jQuery, Novice to Ninja.

Examples

The features I am about to discuss are some experiments I have recently implemented at my movie sharing project sharemovi.es. As JS and CSS code files are nothing secret, you can always go to that site and do a ctrl/cmd+U from you browser to check out how I use this stuff.

1. Autocomplete

I think it was Google that introduced auto-complete: when you start to type a search string you get a list of hits. This is old news (Google went one step further with "Instant search results"), but it is still nice to have on your site. You can get the plugin and see examples at this site. It is easy to implement: a. add the plugin file and css file, b. make a search.php file that queries the database and call it:

$("#search").autocomplete( "search.php", {
  width: 410,
  .. other optional settings ..
 });

#search is the (DOM) id of the searchbox. When you start typing a search string you will see the results of what search.php produced when querying the database. See the plugin's website for more info.

2. Autocomplete -> automatic form submission

As you see in the picture above, I didn't use a submit button. Only a loop but that is a background-image provided by the CSS rule I attached to the input box. Hm.. you select "Goodfellas" and the form doesn't do anything (unless you know you can submit it pressing Enter)

I decided to enhance this with some jQuery. You can use the event.result function to take value of the selected item of the auto-complete list. Then

$('#search').result(function (event, data, formatted) {
..
   var searchVal = $("#search").val();
   $.post("getCleanUrl.php",  
..
     location.href= data;
..

.. in this case: convert the string to the right URL and send the user to it with the location.href function. data is what the ajax ($.post) call returns.

3. Sliding effect between two sets of valaues

On any movie profile page of a user we see nice tabs, these are jQuery (see 4.). I have two sets of values in the first tab: 1. reviewed and 2. rated movies. I distinguish between them with CSS: the reviewed movies have a white background, the rated ones, a gray background. But I wanted the user to filter. Instead of doing various database queries, I decided to let jQuery help me traversing the DOM. First we need to make the two legenda items clickable, so we convert them in anchors, each of them with a unique id:

<div id="legendaWrapper">
   <a id="reviewedTitles" href="#">You Reviewed this title</a>
   <a id="ratedTitles" href="#">You Rated this title</a>
 </div>

Then we need to give each movie row some html classes to distinguish:

<?php $secondClassValue = ($review)? ' movieRowReviewed' : ' movieRowRated' ; ?>
<div class="firstClassValue<?php echo $secondClassValue; ?>">
.. the html of the movie row blabla ..

Now we can hook events to these ids when clicked. It is simple, yet the effect is amazing for this little code:

 $("#reviewedTitles").click(function(){
   $(".movieRowRated").slideUp('slow', function(){
     $(".movieRowReviewed").slideDown('slow');
   });
 });
 $("#ratedTitles").click(function(){
   $(".movieRowReviewed").slideUp('slow', function(){
     $(".movieRowRated").slideDown('slow');
   });
 });

So when we click one of the two categories,  the other will slide up and the selected one will slide down. Of course this could be further enhanced adding a loader.gif during the action to feedback to the user there is something in progress:

$("#reviewedTitles").prepend('<img src="i/loader.gif" id="loading" />');

.. but the sliding in this case is immediate so it is not really necessary. Btw, I love these little progress gifs, you can create them here.

Another important thing to keep in mind is the order of actions. the

... , function(){ .. next action

.. makes that that action is executed after the first one has completed.This is what I want, because it gives some sort of curtain effect. The following snippet would execute both actions at once, and often this gives not the desired result:

$("#reviewedTitles").click(function(){
   $(".movieRowRated").slideUp('slow');
   $(".movieRowReviewed").slideDown('slow');
 });

 $("#ratedTitles").click(function(){
   $(".movieRowReviewed").slideUp('slow');
   $(".movieRowRated").slideDown('slow');
 });

See for more information about callbacks,etc., the jQuery tutorial.

4. Simple Tabs w/ CSS & jQuery

I simply love them. See this example. Only inconvenience is that if you have a lot of content, the tabs are inactive until all the content has been loaded. When the page is loaded, the effect is nice. And the codebase is quite small. See the plugin's website, you can have this up and running in 10 min. :)

5. Toggles

How often you want to hide certain content behind a "more .." button and when clicked, change it to a "less .." button / action. I needed it early on. For example in one of my first designs I wanted to hide a address list behind a "more .." button. I tend to use the plus icon to indicate something more is there. When clicked the plus icon changes to a minus icon and the text changes to "less..". I have to check the source again but you will be amazed how easy jQuery makes it again with the built-in function toggle:

$('.showMore').hide(); 

 $('span.more').toggle(
   function( ) {
     $('.showMore').slideDown();
     $(this).addClass('less');      // **
     $('span.more').text("Hide ..");
   },
   function() {
     $('.showMore').slideUp();
     $(this).removeClass('less');
     $('span.more').text("More ..");
   }
 ); //end toggle
// ** less is a class defined in css which overwrites
//    the plus by a minus background image :
// span.less{... background:url('../i/icons/minus.gif') no-repeat center left}

A toggle effect I recently implemented at sharemovi.es: when clicking the plus icon, you see of what individual votes the average is composed. When clicking 'minus', you go back to the average view. This is a good example of hiding this extra bit of information with jQuery and let the user decide if he/she wants to see it.

I could go on but ..

.. this post has doubled its planned size so I am going to wrap it up. I hope you got to see the power and beauty of jQuery!

I have more favorite jQuery plugins / effects I will share in a second post later this year. There are a lot of nice plugins available which, when used properly (= + right CSS styling), can make your site look fantastic.

I sat down a week back in 09 to try and play with some of jQuery's plugins. It resulted in Galexmoda. Another site I made, which heavily uses jQuery, is Waterdrinker Architects.

What about you?

- Do you use jQuery?
- If so, for what?
- If not, do you use other Javascript libraries / frameworks?

- What plugins/effects do you like?

- Any example sites?

Please let me know ..

How to build a movie trailer API using gData

An important feature of each movie site is trailers, so it is for sharemovi.es! And where should we look for trailers? YouTube! But how can we program to get the corresponding trailer video when inputting the movie title? Use gData!

 

First of all there is a complete YouTube API available, but my solution doesn't require much if any of it. It really comes down to getting the right feed details and parse the XML:

1. First make a query to the gData API (a REST-inspired technology for reading, writing, and modifying information on the web - see also this video: it has been around for quite some time!)

$feedURL = 'http://gdata.youtube.com/feeds/api/videos?q='
  .$q.'&start-index=1&max-results=1';

$q is the movie string to query. the+movie+name+'trailer' works best for me. And we want just the first hit to appear in the feed.

2. Read the feed into a SimpleXML object

$sxml = simplexml_load_file($feedURL);
// and iterate over entries in feed
foreach ($sxml->entry as $entry) {
   // get nodes in media: namespace for media information
   $media = $entry->children('http://search.yahoo.com/mrss/');
   // get video player URL
   $attrs = $media->group->player->attributes();
   $trailer = $attrs['url'];
}

(I found a much more detailed example on the IBM site, but this bit will do for what I want to show ..)

3. Some final tweaking: to embed the gathered URL in a html <object> we need to swap 'watch?v=' with 'v/'. Luckily I played with YouTube URLs before because this is not very obvious.

$trailer = str_replace('watch?v=','v/',$trailer);

.. and we embed the result in the standard embed code YouTube provides to us

<object width="640" height="385"><param name="movie"
value="<?php echo $trailer ;?>?fs=1&amp;hl=en_US"></param>
<param name="allowFullScreen" value="true"></param>
<param name="allowscriptaccess" value="always"></param>
<embed src="<?php echo $trailer ;?>?fs=1&amp;hl=en_US" type="application/x-shockwave-flash"
allowscriptaccess="always" allowfullscreen="true" width="640" height="385"></embed>
</object>

You can see the result on sharemovi.es.

 

I use the jQuery Boxy plugin to present the output as a nice Facebook-like overlay:

A. Click on "View trailer"

B. Overlay with the result of the trailer script that found "The Ghost Writer"'s trailer on YouTube:

Update (09.08.2011)

Some readers requested the source. I put it on Github. Let me know where you roll it out :)


 

Update 20/11/2015:

Gdata is gone, I fixed it by using themoviedb API, see here.

Facebook API: post with PHP

A few weeks ago I wrote a blog post on how to tweet with PHP. The post was quite successful so today part II: Facebook API: post with PHP. The principle is the same: you need to register an app on Facebook and with the API key you can get started.

First you go to Facebook's developer page and add an app. You can name it anything you want but make sure you put the right URL of the site (if you develop on your localhost you might consider register two apps because one api key is linked to one URL)

Then you download the facebook php client library and put in the application key and secret. Then you can use the Facebook login button to have people login to your app.

I am flying over this here because the main thing I wanted to show you today is how to automatically post to your Facebook wall. I will show you an example how I implemented this on sharemovi.es, a site I built to bring together movie fans.

The post that really helped me doing this was on stackoverflow which is one of those resources that always show up in Google, but also provides you with good answers!

Once you have initiated the facebook instance with the php client library, posting to facebook is quite easy:

$attachment = array('message' => 'Check out this movie ..',
 'name' => $title,
 'link' => 'http://sharemovi.es/' . $urlTitle,
 'description' => 'Review: ' . $review,
 'picture' => $picLocal
 );
  if(!($sendMessage = $facebook->api('/me/feed/','post',$attachment))){
  $errors= error_get_last();
  echo "Facebook publish error: ".$errors['type'];
  echo "<br />\n".$errors['message'];
 }

Unfortunately Facebook does not allow you to select a FBCDN image (FBCDN standing for "Facebook content delivery network"), so you have to use another one or copy one from the FBCDN over to your server (hence $picLocal)

The beauty of the Facebook API lays in the fact it is highly customizable. As you can see, you can exactly specify what the wall post should look like, in my case a link to the new movie title, the review submitted by the user, etc.

Now to understand how this works for the user, let's see a practical example: a user logs into sharemovi.es via the Facebook login button. The first time the user is asked by Facebook to confirm if the Facebook app/ sharemovi.es may access his/her personal info, email and since last week the extended permission to post to his/her wall. Below you see only the latter permission, because the basic permissions I accepted already.

This allows the app to post to the user's wall, but that is only possible when a valid Facebook session has been established (user has logged in).

Implementing this technique, I made the design choice to explicitly ask the user to use this feature. This way there shouldn't be any misunderstanding when sharemovi.es posts to your wall.

Finally here you can see the outcome: a nice customized wall post!

You will recognize the fields of the code snippet. Friends can like and comment on your post, just as any link you share with the existing Facebook buttons. Below the post you see the source, which is the application, Sharemovi.es in this case.

One final thing, you can easily delete the post and even, in the same menu, revoke all access the Facebook application has been given. Facebook thought this out well: your granted access is never permanent and as easy as you give it, as easy it can be taken away:

I hope you liked this post. If so, please use the social media buttons at the top and the bottom of this post to spread the word. You can also subscribe to this blog (see sidebar) to receive a periodic newsletter with my latest blog posts.

Clean URLs not just an option ..

First of all Happy New Year! I hope you'll all have a 2011 full of inspiration and interesting work on the web. A quick post to kick off the New Year. Why are Clean URLs important? And how to set them up painlessly thanks to Apache's mod_rewrite module.

There are many reasons to use clean URLs. First of all the cleanness. A long query string seems garbled and you certainly won't remember it when somebody asks for it. Facebook introduced it in 2009 (quite late as this is out there much longer). Now compare http://www.facebook.com/bbelderbos with http://www.facebook.com/profile.php?id=628517118 .. the latter is hard to remember and .php and id are not relevant for the average user, right?

Second SEO. Google's Webmaster guidelines outline: "If you decide to use dynamic pages (i.e., the URL contains a "?" character), be aware that not every search engine spider crawls dynamic pages as well as static pages. It helps to keep the parameters short and the number of them few." So it is best to be short but informative in your links.

Moreover, it's the standard. About any CMS has this feature integrated. Take Wordpress: check the URL of this post you see domain -> year -> month -> slug of the post. It is informative, it tells the title and year/month of the post. Moreover, instead of page.php?id=1234&foo=5678, it contains keywords which are of relatively high value for search engine indexing. So clean URLs make for a better search engine ranking!

So now to the techie part, how can we make them? It is rather easy! Take for example sharemovi.es, I have an index page that gets a GET variable called "t" with the value of the user, here "bbelderbos". This means it will get data from the database according the user it gets inputted.

Now I want to have this translated to :

Enter Apache's mod_rewrite. You'll need to make/edit a file called .htaccess at the same level where the script (index.php) file is located. All it takes are the following two lines:

RewriteEngine On
RewriteRule ^(\w+)$ index.php?t=$1

- The first line lets Apache (the webserver) know that you want to rewrite URLs

- The second line actually defines the rewrite action. It starts with a regular expression: '^' to start the string, '(\w)' to match a word, then '$' to mark the end of the string. This will match a string that is stored in variable '$1'.
Then it defines the rewrite pattern: index.php?t=$1, so filling it with what it retained in $1 it will translate 'bbelderbos' to 'index.php?t=bbelderbos'. The beauty of this it's done under the hood: while the user is presented with the tidy URL, the server receives the full info it will need to generate the page: index.php?t=bbelderbos

See more examples of rewrite rules in this article or simply google 'mod_rewrite'. To write (complicated) rewrite rules, requires some knowledge of Regular Expressions. Oreilly has some interesting titles on the subject, but you can easily get along checking out almost any PHP or programming tutorial. I like the introduction on regex given in this PHP book.