Archive for the ‘technical level’ Category.

How to use JSON (updated with example)

This post is an update from the old post. A lot of things changed since it was written and the information in the old one is a bit outdated.

First of all, you should never use an eval() when using JSON because of security reasons that I will talk about later in another post. [edit : jQuery uses eval() but there's a work-around that will be talked about in another post.]

JSON and jQuery

The simplest way to use JSON is though jQuery. I have been using for more than 2 years and I never was disappointed.

Let’s say I want to call Flickr search with JSON. It’s simple :

  1. $.getJSON(
  2.         "http://api.flickr.com/services/rest/?jsoncallback=?",
  3.         { method : "flickr.photos.search",
  4.                 api_key : "4ef2fe2affcdd6e13218f5ddd0e2500d",
  5.                 format : "json",
  6.                 tags : "landscape",
  7.         },
  8.         ajaxCallBack
  9. );
  10.  

The $.getJSON takes 3 parameters.

1. The URL
The URL of the remote call.

2. The parameters
The parameters to complete the call. On the documentation page about this Flickr method, you have a list of all the parameters you can use. For a JSON call on Flickr, you have to send the api_key and the format. I added the parameter tags to send me all photos that are tagged landscape.

3. The callback
Most API services now requires a callback, a method that will be called when the JSON is loaded. It is more secure and easier to work with. At the end of the first parameter (the URL), I added jsoncallback=? (flickr called this parameter jsoncallback but it could be named differently on other services). This is the jQuery-way of saying “When you finish loading the JSON, call the method specificied by the third argument”.

You may wonder how Flickr knows which function to use on callback. It’s because in jQuery, there’s a special case for that. In the URL, you can see that the jsoncallback is written like that jsoncallback=?. The ? is replaced by your own callback method (in my case, I called it ajaxCallback)

The callback method

The callback method I used looks like this :

  1. function ajaxCallBack(data) {
  2.         // Loop throught all photos and display them
  3.         // it uses the jquery.each method
  4.         // doc at http://docs.jquery.com/Utilities/jQuery.each
  5.         $.each(data.photos.photo, function(photoIdx, photo) {
  6.                 // Build the thumbnail url
  7.                 var thumb_url = ["http://farm", photo.farm, ".static.flickr.com/",
  8.                         photo.server, "/", photo.id, "_", photo.secret, "_t.jpg"].join("");
  9.                
  10.                 // Build the photo url
  11.                 var photo_url = ["http://www.flickr.com/photos/",
  12.                         photo.owner, "/", photo.id].join("")
  13.  
  14.                 // Build HTML
  15.                 $("body").append(
  16.                         $("<a>")
  17.                                 .attr("href", photo_url)
  18.                                 .attr("target", "_blank")
  19.                                 .append(
  20.                                         $("<img>").attr("src", thumb_url)
  21.                                 )
  22.                 )
  23.         });
  24. }
  25.  

If you know jQuery a little, it simply creates the HTML to show the thumbnails and a link to the photo.

Get the code

You can get the complete code for this example on GitHub and a working example.

Easy loop for every element of an array

There’s something bugging me with javascript for loop : the extra work to loop though all elements of an array. Suppose I want to alert each element of an array, there are three ways of doing it.

First, you loop with an index and assign the element to a variable.

  1. var items = ["a", "b", "c"];
  2. for (var i = 0; i < items.length; i++) {
  3.   var item = items[i];
  4.   alert(item);
  5. }

You always have to have that extra assignment at the beginning of the loop.

Second, you loop with a for each.

  1. var items = ["a", "b", "c"];
  2. for (var i in items) {
  3.   var item = items[i];
  4.   alert(item)
  5. }

In javascript, the for each loops though the index of the array instead of looping though the elements, like in most other languages. Thus, you also have to make the extra assignment at the beginning of the loop.

The easiest way of doing it is the third one.

  1. var items = ["a", "b", "c"];
  2. for (var i = 0, item; item = items[i]; i++) {
  3.   alert(item);
  4. }

How does it work? First it uses multi-assignment on one line. In javascript, you could write var i = 0, j = 1; and it would create two variables, i and j.

The second part of the for is confusing : it assigns the item but it never check if i it is out of bounds of the array (using i < items.length). It works because when javascript tries to assign an item after the end of the array (in our case items[3]), it returns null which is considered by javascript as false.

Cleanest way of executing javascript code on page load

Everytime that I work on a new project, I’m always unsure about which way to execute javascript on page load. These are the different techniques :

Your old buddy body.onload()

The safest way to execute javascript when a page loads is to use the body.onLoad method.

  1. <body onload="doSomething();"></body>

The document.ready function with jquery

This technique requires jquery and is similar to the body.onLoad technique (see above).

  1. <body><script>$(document).ready()</script></body>

The problem is that I don’t like that the javascript code is too close to the HTML code. There’s really something that I don’t like.

The #ID.ready

DO NOT USE! It doesn’t work. At first, I tought that this technique worked but in fact, even if the element corresponding to the ID doesn’t exists, the function is called. To understand it better, I’ll give you an example. Suppose that I want to load a user list with ajax after the page load and that list correspond to ul#users, I’d write the following code

  1. $("ul#users").ready(function() {
  2.   loadUsersWithAjax();
  3. });

Unfortunately, it doesn’t work.

The document.ready + #ID.each

After the failure of the #ID.ready technique (see above), I tried a similar thing that is working but ugly looking. Suppose I want to do the same as above, I’d write this :

  1. $(document).ready(function() {
  2.   $("ul#users").each(function() {
  3.       loadUsersWithAjax();
  4.   });
  5. });

That way, it would execute the loadUsersWithAjax() method for each ul#users and because element IDs are unique to a page, the method would be called only once. It looks bad but it’s the “prettiest” way I found of executing javascript code on page load.

Now, I want to know what would you suggest? Which technique is your?

JavascriptKata now ad free

[Update 2009-09-20 : I will try to bring back ads. I removed them because I was frustrated, I bring them back as an experience.]

JavascriptKata was created in the blog bubble. In a time when all you had to do was to create a blog, put ads on it and you were rich. It never was true. The ads on this blog gave me about 100$ in a year so I finally felt discouraged and left it for dead. Nevertheless, this blog as a good share of traffic and more subscribers in the feed than any blog that I’ve owned/I own/will own. In fact, I call it a blog but it’s not really a blog. I used wordpress and that’s the main reason why I’m calling it a blog.

I tried several things to keep my interest in writing about javascript but they all failed because there was the devil saying “anyways, you don’t make any money out of it”. But there was the angel saying “maybe you don’t make money but you like javascript and should continue to write about it”. As usual, the devil won.

I won’t try to make another revival of this blog but I’ll try to write more about little things that happens between me and javascript, about the daily problems that I encounter. I’ll write a lot about jquery too since for me, there can be no javascript without jquery.

Thanks to all of you!

Load a page with javascript

I receive javascript-related questions in my inbox from time to time and here’s the last one.

I am ok with HTML but awfully new to JavaScript and I know very little at this point. My question is for this web site I’m building. I need to know the exact JavaScript code and placement of the code in an HTML document for this goal. I would like this site to automatically load a certain page (1-31) depending on what day of the month it is (1-31). I don’t need to worry about what month or year it is, just the date in the month. For instance when it is the eleventh day in the month, page11.html will automatically load when you click on to the site. I would like it to take the time(Date) from the client side not the server. This way no mater what time zone your in the right HTML page will pop up at midnight.

Most people can’t give the exact javascript code placement of the code in an HTML document because it would always be buggy. They can give hints and/or snippets of code but rarely a complete working piece. Sorry…

Secondly, relying on javascript to do all this work would be a mistake because if javascript is disabled, the site will not work. Most users have javascript enabled but you should always think about web-crawlers (google, yahoo!, etc) that will try to index your page but will hit an empty page.

It’s always hard to guess all the reasons why someone would want a different page everyday of the month and I don’t know more about the project than what is written above. Considering this, maybe there are just parts of the page that are changing everyday and you could load them on the server-side thus having a single page loading including other pages depending on the day. The problem is that you would have to ask the timezone of the user and keep it in a cookie.

Just remember, javascript should not be a requirement to navigate in a site.

Finally, if I would really want to load a complete new page in javascript, I would do the following.

  1. var dayOfTheMonth = (new Date()).getDate();
  2. location.href="page" + dayOfTheMonth.toString() + ".html";

 

This is the way I would do it, do you have any other suggestions?

How to have jQuery and prototype.js in the same project

I’m a big fan of jQuery. This librarie is just the best and simplest one around. I really noticed it when I wanted to get rid of jQuery in TimmyOnTime and try to use prototype.js instead, just to be more “rails-oriented” (that’s a pretty lame excuse don’t you think?)

Why I didn’t like prototype.js

There was not a lot of javascript written for the project so I thought that getting rid of jQuery and using prototype.js would be easy. It turned out to be hell on earth. Prototype.js made me feel like I was back in the 90s writing C++. A simple click event turns out to be a awful lot of ugly code with ugly function names.

Example, if I wanted to show the content of a DIV I clicked in prototype.js, I would use things like Event.observe, bindAsEventListener, a mix of native DOM element and prototype.js element, and worst of all, an unintelligible documentation.

jQuery as a complete different way of doing it in a single easy-to-understand line :
$(“#a_div”).click(function() { alert($(this).text()); });.
As simple as that!

The problem

I wanted to use some interface element in Rails that requires prototype.js so I had to have both librairies. The problem is that there’s a conflict between them. Prototype.js doesn’t seem to give a damn about it but jQuery is nicer with you. It offers a noConflict method.

With Rails, prototype.js is the default librairie so to override this, you could do

  1. <%= javascript_include_tag "prototype", "jquery" %>
  2. <script>$j = jQuery.noConflict();</script>

This way, you will have to use $j instead of $ to call jQuery.$ would still call prototype.

Another thing you could do is to use jQuery on Rails and don’t give a damn about scriptaculous. I personally prefer to use librairies that are fully tested instead of using a “by-pass” that could break my code. It’s your choice…

New on Javascript Kata : the echo chamber

Since the beginning of the new year, I’m offering to javascripters the echo chamber. What is it? It’s a category where I will post news about what happens in the javascript world. I will try to avoid ajax related news because Ajaxian already does the job really well.

You can subscribe to the RSS feed with all the articles or to the RSS feed without the articles from the echo chamber.

Some may have noticed that I redesigned the site. The old design was long overdue and it was a pleasure for my eyes to have a new one.

I would also like to have your feedback on what you think of the new echo chamber and design?

Ask Dan : More on javascript threading

From time to time, I receive emails from desperate people who want help with their javascript problem. I also receive a lot of emails of people wanting to help me with my “manly problems”. It’s very nice from them to care about me and I take time to reply to each of them but I don’t have that kind of problem for the moment.

Stuart Cooper recently sent me a mail about threading in javascript and I turn to you, javascripters, to find the a solution for his problem. I sent the code on RefactorMyCode for refactorisation and they will automatically show up in the comments of this post (the site is an idea of Marc-André Cournoyer who is a very active developer from Montreal). Don’t be afraid to think outside the box. The solution may be completly different from what is already written.


I am experience trying to create a “cover page” that runs a ping to remote servers.In my code I am using setInterval() to run repeating pings (artificially quickly at the moment, ie 10 seconds rather than 1 min) and display the results to browser. I have built my own XMLHttpRequest module (mainly as a learning exercise) and I don’t believe it to be the source of my ills. I have read through your article and the behaviour of alert() and confirm() fits exactly with what I am seeing when I run the following code :[snippet]

function startup(){

setInterval(“pinger(‘live’,0)”,10000);
setInterval(“pinger(‘standby’,1)”,10000);
setInterval(“pinger(‘dev’,2)”,10000);
setInterval(“pinger(‘test1′,3)”,10000);
setInterval(“pinger(‘test2′,4)”,10000);
setInterval(“pinger(‘test3′,5)”,10000);
setInterval(“pinger(‘test4′,6)”,10000);

}

function pinger(server,divit){

console=document.getElementById(‘ping_div’ + divit);
console.innerHTML=”;
sendRequest(“../php/ping_sys2.php?target=” + server);

}

[/snippet]

(each server has its own named div to return to)

What I am seeing when I run this is the final pinger response from the callback and nothing else. I since added debugging into my XMLHttpRequest code so that it split out the server response progress.

[snippet]

readyXML=xmlReq.readyState;

[/snippet]

[snippet]

if(readyXML == 3){

data=”Serving …”;

}

if(readyXML == 2){

data=”Sent …”;

}

if(readyXML == 1){

data=”Opening …”;

}

[/snippet]

What I have observed is that when running the setInterval commands as above, all except the final request are “jammed” on readyState = 1 and appropriately responds with “Sending …”

however,

when I do the following (which is messy)

[snippet]

function startup(){

setInterval(“pinger(‘live’,0)”,1000);
alert(“something”);
setInterval(“pinger(‘standby’,1)”,10000);
alert(“something”);
setInterval(“pinger(‘dev’,2)”,10000);
alert(“something”);
setInterval(“pinger(‘test1′,3)”,10000);
alert(“something”);
setInterval(“pinger(‘test2′,4)”,10000);
alert(“something”);
setInterval(“pinger(‘test3′,5)”,10000);
alert(“something”);
setInterval(“pinger(‘test4′,6)”,10000);

}

[/snippet]

Each response is absolutely spot on and will continue to generate pings correctly. So in this case the script alert interrupts are forcing the callback request to trigger, whereas without the alerts its only the last request that triggers a callback. I have also tried using artificial timeout loops instead of alerts (which generate the odd browser “script running slowly” message) but to no avail.

At the moment I am almost resigned to having to create individual events (like rollovers, though I would much prefer the ping initialisation to occur window.onLoad()) that trigger the setInterval() … which also seems to work fine.

I am hoping that you may have come across a way of forcing the XMLHttpRequest to respond without forcing alerts or confirms on the user, in the time since the last update to the article.

A new project – I hate PHP

If you are javascripter, chances are that you must work with some back-end languages like ASP.NET, ColdFusion, Ruby On Rails or PHP. If you work with a back-end language, chances are that you become frustrated against it sometimes. That’s why I created I hate PHP.

What is it?

I hate PHP helps you to evacuate your daily frustrations against the PHP language via Twitter. It’s simple. You must tell your twitter username to I hate PHP (on the website) and then, send a direct message to the ihatephp twitter user in the following format : d ihatephp a thing that frustrates you in PHP.

Why against PHP?

I could have done it against a lot of languages because they all suck in their own special way. But the moment I was thinking about the project, I was working with PHP and I just kept sending IM messages to Frank (of Ruby Fleebie) to tell him about things that frustrated me in PHP. I just made it more “official” and now I tell it to the world via I hate PHP.

Subscribe to the RSS of I hate PHP!

Barcamp Montreal 3 and this site

Like most of you already knew, I’m working with Frank Lamontagne of Ruby Fleebie on a project called TimmyOnTime. We had the chance to present it at the last Barcamp Montreal and it went… really bad! If you want to know more about the whole adventure (and have a good laugh), click here to read the story written by Frank. (By the way, I used a good ol’ click here link just for the fun of it… I never did it before and frankly, I like it… almost…).

What happens with Javascript Kata?

I know, I have been negligent with site. It’s really shameful to let a great site die and there’s no one to blame but me. Why I did that? I could give hundreds of reasons but they would all be lies. I really don’t know what happened.

I want to give another twist to JavascriptKata. I want to get back to a more tradional reference site because I don’t like the concept of a technical blog after all. I want the articles to be more persistent, not just a post that everyone forget about after a while.

But, there would be a RSS feed too. I would announce new articles on the site. I would also use it to debate on tricky things about javascript and then make an article out of it.

I really would like to hear you about this idea, please comment!