Archive for the ‘ajax’ Category.

How to write a simple undo system for your app

I really like undos. If I could undo that that last beer… Unfortunately, I can’t. But, I can offer undo to users of my application.

When I thought about undo before, I thought about a complicated Rails plugin that would keep an anonymous ID linking to any table in the database with an “action” field that would contain the action to undo. Pretty complicated stuff for something as simple.

The javascript solution

One day while I was writing some javascript, the solution struck me : I could handle this completely with javascript. The basic idea is that whenever an action is completed, I can save its undo function in an array and call it whenever I need it.

Example, if I’m saving a user in a database with Ajax :

  1. I send the data to server to save a new user
  2. The server returns the ID of the new user
  3. I create a function with an ajax request that will send a delete of this user to the server
  4. I add the previous function to a stack of undo functions to be able to call it later

That, when I call that last function, it will undo that user creation without having to keep it in memory server-side.

Introducing jsKata.undo

I wrote a little something called jsKata.undo on GitHub that contains the logic describe earlier. It’s quite simple but it may grow over time. It has no requirement, not even jQuery. It’s very simple to use.

The complete doc is on GitHub.

1. Adding an action that can you can undo

I’ll use the “add a user” example with jQuery.

  1. $.post(
  2.   "http://yoursite.com/users/new", // The url to add a user
  3.   {name:"John Boucher"}, // The name of the user
  4.   function(newUser, textStatus, XMLHttpRequest) {
  5.     // This is called when the post is over
  6.     var newUserId = newUser.id;
  7.  
  8.     // We begin by creating a function to delete the user
  9.     var undoNewUser = function() {
  10.       $.post(
  11.         "http://yoursite.com/users/delete", // The url to delete a user
  12.         {id:newUserId} // The ID of the new user to delete
  13.       );
  14.     }
  15.  
  16.     // We add the undo function to the stack
  17.     jskataUndo.push(undoNewUser);
  18.   }
  19. );

2. Undo the last action you made

  1. jsKata.undo.undo();

3. Events

Each time there’s a change, an onChange event is called. To assign yours, simply write :

  1. jsKata.undo.onChange = function() {
  2.   // Show the undo button
  3.    $("#undoButton").show();
  4. }

There’s also an onEmpty event that is called when the stack of undoable actions is empty.

  1. jsKata.undo.onEmpty = function() {
  2.   // Hide the undo button
  3.    $("#undoButton").hide();
  4. }

Complete demo

There is a complete demo on GitHub as well as the HTML and Javascript code for it. Take a look!

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.

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.

Ajax, javascript and threads : the final truth

Since I have written Ajax and javascript don’t use thread, one of my reader (BK) told me that I was wrong. Here’s the final truth.

What I said

If javascript runs some code that takes 5 seconds to execute and an ajax response arrives at 2 seconds, it will take 3 seconds before it will be executed (before the callback function is called).

Example. We have a f() function that is incredibly long to execute (5 seconds) because it has a lot of code.

1. function f() is started
2. f() makes an ajax call
3. f() is still executing since 2 seconds
4. the response from the server arrives at the third second
5. f() is still in execution for 3 seconds
6. the callback function for ajax is called

What he said

Briefly, say I have CallPage1, CallPage2 and DoSomething. Both CallPage are async.

CallPage1 called
CallPage2 called
DoSomething called
CallPage1 Returned (DoSomething is now paused)
DoSomething ended
CallPage2 Returned

The DoSomething() function is paused when the ajax response arrives. The callback for the ajax is called and only then, DoSomething() resumes its execution.

That didn’t make sense to me. Javascript is really sequential and it would not do that kind of complex stuff. But, I had to be sure.

The test

I made a simple page to test it all.

1. Loop from 0 to X (user defined). X should be a big number.
2. The first loop, it makes an ajax request
3. The loops will finish someday
4. The callback for the ajax will be called someday

I didn’t know what to expect : will the callback function be called before or after the loop?

The result

I ran the script a lot of times with a lot of numbers and it was always the same thing : the callback function waits for the loop to be over before it is executed. It means that the current function is not paused.

Now it’s your turn

I want you to take a look at the script (complete php code) (I know it’s poorly written, it’s just a test) and tell me if I’m wrong or if I’m right.

Thanks to you all!

Ask Dan : Procedural VS object-oriented in javascript

Since the beginning of Ask Dan a javascript question, I received a bunch of questions. Here’s the first one I received. It’s from Andrew Worcester.

There seems (to me anyway) to be an overuse of the “new” syntax in libraries. If I create an Ajax object is there a functional benefit to using: “new Ajax.Request(options)” verses something like “sendAjaxRequest(options)” It seems to me that by using “new” causes more hassle because you need to be sure the objects are properly disposed of. So is there a performance or functional benefit to this technique?

I had a hard time understanding the question (and I was too ass hole to ask…) so I’ll rephrase it in another way : is there a benefit from using object-oriented techniques VS procedural in javascript?

Procedural in javascript

Though javascript was not a procedural language from the start, it has been overused as such in the beginning (and it’s still is). That may be because people didn’t bother learning javascript and they copy/pasted functions from sites that offers low-quality javascript snippet. All they did was “hacking” the poorly written code to suit their needs. This technique worked for a long time but with the use of ajax and DHTML, it’s nearly impossible to have clean code that is not buggy and dirty.

Object-oriented in javascript

The new statement necessary implies the use of objects in javascript. You can have basic information about object in How to create objects in object-oriented javascript and in with the articles tagged Object-oriented of this site.

The benefit of object-oriented

There is one major benefit about object-oriented that creates a lot of other benefits : the cleanliness of the code. The other benefits from that are : the code is easier to maintain, to modify, to read and to explain.

OO applied

I’ll apply it to an example. I want to alert the sound of cat by ajax.

In a procedural way, you’ll approximatively have

  1. // Global variable
  2. ajaxRequest = null;
  3.  
  4. function sendCatSoundAjaxRequest() {
  5. ajaxRequest = new XMLHttpRequest(); // Create the request in the global var
  6. // … code for request …
  7. }
  8.  
  9. function receiveCatSoundAjaxRequest() {
  10. // The sound is in clear text in the response
  11. alert(ajaxRequest.responseText);
  12. }

The problems? You have a global variable to keep track of the ajax request. Because it could be use by every other functions that need ajax, you can’t make more than one request at a time. Also, there are nothing that binds the two methods together apart their names that are look alike. Now, just think of the code when you have 5 or 6 different type of requests. Your code will look like garbage.

In a object-oriented way, you would all write this ugly code in a separated object. Your main call to see the sound of a cat could be something like

  1. var cat = new Cat();
  2. alert(cat.getSound());

The code from above still exists somewhere but the complexity is now hidden behind the Cat class.

Ajax and javascript don’t use threads

Since ajax, a lot of people are thinking that asynchrone means “in a separated thread”. They are wrong!

Synchronous

The XMLHttpRequest object gives you the option to make a synchronous request to a server with the parameter async set to false. It means that when you call the server, all javascript executions will stop and wait for the server to respond to the request. I never saw it used. In fact it is more confusing that anything else because the page seems frozen and users don’t like frozen things. If you use it, you are not cool!

Asynchronous

Now you are being cool! The asynchronous is used by everyone and it doesn’t freeze the page while the call to the server is done. So, if you have a call that takes 30 seconds before receiving the answer, your users will never know that you’re a bad server-side coder that do not optimize the code he’s writing (I’m just joking).

The misconception of asynchronous

People take for granted that because it’s asynchronous, it’s a thread. They are partially right. There must be a thread created by the browser to keep the javascript running while it makes a request to the server. It’s internal and you don’t have access to that thread. But, the callback function called when the server responds to the ajax request is not in a thread.

I’ll explain clearer. If javascript runs some code that takes 5 seconds to execute and an ajax response arrives at 2 seconds, it will take 3 seconds before it will be executed (before the callback function is called). That’s because javascript itself doesn’t create a thread to execute the ajax response from the server and simply waits that all executions are terminated before starting a new one.

So if you’re running a lot of ajax requests simultaneously, you might get some weird behavior because they will all wait one on another before executing themselves.

#UPDATE 2007-06-12
Following one of my readers comment (BK), I have written a sequel to this article : Ajax, javascript and threads : the final truth.

3 reasons why I use jQuery

These days, you can’t write a web application without using one of the billionth javascript library. Two of them stood out of the crowd : prototype and jQuery. I will explain why did I choose jQuery.

Prototype

Prototype is comfortably installed in a lot of developers mind because of two reasons : it was the first widely used and script.aculo.us. Being the first accepted library is a hard thing to do and it will always help them. Scriptaculous (I hate to write it with the dots) had an incredible effect on the popularity of prototype. For the first time, we could do “flash animation” without using flash. This was instant popularity.

jQuery

jQuery is one of the bastard child of prototype. It reuses the $() function but brings it to a level you never could have hope for. In fact, jQuery is almost completly based on the $ sign. Why? Maybe because it’s fast, maybe because it’s trendy. I don’t know. Example, you want to download a JSON from a server, $.getJSON(“http://www.thesite.com/thejson”).

Reason #1 : The selectors

jQuery supports a lot of selectors. And when I say a lot, I really mean a lot. First, there’s CSS selectors. You just have to apply what you know about CSS and you can write many complex selectors.

Second, there’s XPath selectors. When I was young (sic!), I wrote a lot of XSL. And when I say a lot, I really mean a lot. XSL makes an intensive use of that XPath thingy. Because XHTML is basically XML, we could use XPath to easily navigate throught the DOM. The problem was that before jQuery, nothing could do that. Now, we can!

In comparison, prototype just has the $(‘theId’) to select a element. Ouch!

Reason #2 : The Attributes

It’s easy to add/remove attributes to any HTML element. I use it when I create new elements or when I need to add/remove a css class on an element. The interesting thing is that you can chain them and it will work. Example, I want

  1. $("div").attr("title", "This is a div").addClass("newClass");

You can add as many as you want…

Reason #3 : Ajax and JSON

Once again, ajax is now easy as 1,2,3. I wrote an article on JSON and in my mind, there’s no real alternative to JSON. jQuery helps you with it.

  1. $.getJSON("http://www.thesite.com/thejson",
  2.         function(json){
  3.                 alert("I received the json and put it in the json var : " + json.toString());
  4.         }
  5. );

It’s a little more complex with prototype.

How to use JSON

UPDATE : This was written more than 2 years ago, read the new post on How to use JSON.

Web2.0 came with the intensive use of the XMLHttpRequest object even if it was already in our browser before then. A lot of format were tried but JSON will be the winner overall.

What is JSON?

JSON is a format for communication between the server-side (PHP, ASP.NET, …) and the client-side (javascript). The magic of it is that the response from the server-side can be easily converted to an object via the use of the eval() function.

Eval() is a function that gives you the possibility to execute some code in javascript from a string.

  1. eval("alert(‘This is from eval()’)");

This is a bad idea to use it in your code but so easy for JSON that you have to use it.

How to JSON on the server-side?

You can work like an idiot and create your own JSON marshaller for your project or you can go to json.org and use one of the objects that you can find.

I’ll take PHP as example. You want to send an object to javascript. You simply do

  1. $response = array();
  2. $response["id"] = 3;
  3. $response["message"] = "The object was saved";
  4. echo(json_encode($response);

It will echo

{id : 3, message : "The object was saved"}

How to JSON on the client-side?

Use the eval() function.

  1. var json = eval(theServerSideJsonTextResponse);

You can now use the json variable created like this

  1. alert(json.id + " : " + json.message);

and it will alert

3 : The object was saved

Beware!
There may be an invalid label error here. The solution is to add parenthesis to the response.

  1. var json = eval("(" + eval(theServerSideJsonTextResponse); + ")")

#UPDATE : May 10, 2007
As it was pointed out in the comments, you should never use eval directly when parsing JSON on the client-side. Use a existing JSON parser or a library (jquery is my favorite).

Other formats

For sure there are hundreds of ways of sending back a response to javascript but to my experience, JSON is the best. Let’s take a look at the others.

XML is for purists with a lot of time to spend
Do you really want to write a XSD (or DTD) for all the calls that can be made to the server? Anyway, it’s long to develop because you have to parse it all.

HTML is for lazy people
Though it’s not completly wrong, laziness is often a bad thing. What do you do if you want to reuse information that you got in a HTML? You parse the HTML to extract the info? please don’t…

CSV is for the people that are stuck in the 90s
CSV was the coolest thing back in the 90s along with Fresh Prince of Bel-Air.

Watch out for BISON

BISON is nothing else than Binary JSON (see this article). It’s lighter than JSON but still unstable. My guess is that we’ll all use it sooner or later… but it’s just a guess…

How to use javascript hashes (or hash-table)

Javascript has no hash table object. In fact, all objects are hashes.

  1. var hashPetName = new Object();
  2. hashPetName["dog"] = "Rex";
  3. hashPetName["cat"] = "Mistigri";
  4.  
  5. console.log("My dog’s name is " + hashPetName["dog"]
  6.         + " and my cat’s name is " + hashPetName["cat"] );
  7.  

It’s a little overwhelming to write it like that so let’s use a simpler form.

  1. var hashPetName = {
  2.   dog: "Rex",
  3.   cat: "Mistigri"
  4. }
  5.  
  6. console.log("My dog’s name is " + hashPetName["dog"]
  7.         + " and my cat’s name is " + hashPetName["cat"] );
  8.  

Great! That’s it about javascript hashes, now I can go groom my cat.

Wait!!!

Why can I use an object to emulate a hash? Can I do the same thing with a Number object? Let’s try with the same code than above but with a Number instead of an Object.

[source:javascript]
var hashPetName = new Number(); // Magic is here!
hashPetName["dog"] = “Rex”;
hashPetName["cat"] = “Mistigri”;

alert(“My dog’s name is ” + hashPetName["dog"]
+ ” and my cat’s name is ” + hashPetName["cat"] );
[/source]

It works!!! What can we understand of this?

All objects are hashes too

When you are javascripting, forget everything you know about other languages, it won’t be any help.

I’m adding to the list

  • All objects are hashes

When we create an object, its properties and methods are added to the hash of the object.

[source:javascript]
// Create a class
function TheClass() {
// Adding a property
this.name = “the name”;
}

// Create the object
theObject = new TheClass();

// Alert the property name
alert(theObject.name);

// Alert the property name using the hash
alert(theObject["name"]);
[/source]

In this example, you see that using theObject.theProperty is the same thing that using theObject["theProperty"].

Dynamically add a property/method to the object

In my first example, I didn’t create the property in the constructor before using it. As you saw, it’s easy to dynamically add a property or a method.

[source:javascript]
// Create a class
function TheClass() {
}

var theObject = new TheClass();

theObject["age"] = 3; // Create a new ‘age’ property
theObject.fullName = “Mistigri”; // Create a new ‘fullName’ property

theObject.alertDetail = function() {
alert(this["fullName"] + ” is ” + this.age);
}

theObject["alertDetail"]();
[/source]

Beware! The new property/method will only be available to the instance you’re working on. If you want to add a new property/method to every instances of the class, use prototypes.

Using an array thinking it’s a hash

One of the most common mistake I see is to use an Array object thinking that’s the only one that you can use the brackets to create a hash. Even if it works, it’s not how it should be done. I recommend the use of Object instead.

[Update : A friend of mine pointed me out that I should have talked about hash tables (or associative arrays) instead of hashes.]