Tag Archives: ajax

Failproof AJAX requests in Firefox OS

Have correct values in the manifest

The app type has to be at least privileged. No, web (hosted) apps won’t work with different domains if CORS is not enabled there.

Add the systemXHR permission too, or your XMLHttpRequests to domains without CORS enabled will instafail.

Example of the syntax for these two things in the manifest:

{
  "type": "privileged",
  "permissions": {
    "systemXHR": {
      "description": "Allows loading remote content"
    }
  }
}

Add the “magic word” when creating XMLHttpRequest objects

The magic word being the mozSystem property:

request = new XMLHttpRequest({ mozSystem: true });

You should now be able to use the request in the usual way. Remember to add an error handler in case it fails!

We are using these superfailproof requests in our privileged app template to load definitions from MDN. Have a look!

For more info

JSONP explained

I had heard about JSONP several times before, but as I didn’t need to understand it yet, I had just ignored any of the usual reference materials about it… until today. I was trying to access some feeds via ajax and noticed that even if they “loaded”, with readyState being 4 and all that, the response body was empty. I first wondered if it was because I was executing my script locally, and maybe the feeds host wouldn’t like to see clients using localhost servers, who knows?

I was wrong, it was just the usual cross domain problem. There are three solutions:

  1. use an internal proxy to fetch data and send it to your javascript code. For example: proxy.php will fetch all the external feeds on behalf of your code.js, which will call proxy.php for all its requests. This, apart from adding extra load in your server, defeats the whole purpose of doing client side scripting for retrieving the external feeds data.
  2. use a flash proxy and communicate with it from your javascript code. Not something I want to do, since I didn’t want to use flash for this.
  3. use JSONP

And what is JSONP? In essence, dynamically creating a new SCRIPT element in your document. Its URL will be the URL from the feed service; and when it finishes loading, it will execute. But here’s the trick: the URL has a special parameter, usually named callback. This parameter is used in the response from the server, in such a way that the response is actually a function call whose parameter is the JSON data you expect.

Confusing, huh? OK, it’s easier with an example. Let’s say you want to grab the latest pictures from the tortoises pool in flickr. It has an RSS feed: http://api.flickr.com/services/feeds/groups_pool.gne?id=78811852@N00&lang=en-us&format=rss_200

Notice the format=rss_200 parameter?

If you change it to format=json you get something like this:

jsonFlickrFeed({
                "title": "Tortoises, turtles and terrapins - zoo, wild or pets Pool",
                "link": "http://www.flickr.com/groups/tortoise/pool/",
                "description": "<a href=\"http://flickr.com/groups/78811852@N00/\"><img src=\"http://bighugelabs.com/flickr/profilewidget/group/random/000000/ffffff/78811852@N00.jpg\" alt=\"Tortoise. Get yours at bighugelabs.com/flickr\" title=\"Tortoise. Get yours at bighugelabs.com/flickr\" /><\/a> A group for, you guessed it, Tortoises, turtles and terrapins, they can be wild, zoo or pets. There is a group for pets only - <a href=\"http://www.flickr.com/groups/pet_tortoise/\">&quot;PET TORTIOSE&quot;<\/a> Comment code below, Seen in <a href=\"http://www.flickr.com/groups/tortoise/\">&quot;Tortoises, turtles and terrapins - zoo, wild or pets&quot;<\/a>",
                "modified": "2009-07-28T20:37:25Z",
                "generator": "http://www.flickr.com/",
                "items": [
           {
                        "title": "Schildkröten_2009",
                        "link": "http://www.flickr.com/photos/testudograeca/3762164698/in/pool-78811852@N00",
                        "media": {"m":"http://farm3.static.flickr.com/2573/3762164698_6f27527c81_m.jpg"},
                        "date_taken": "2009-07-26T12:54:13-08:00",
                        "description": "<p><a href=\"http://www.flickr.com/people/testudograeca/\">TestudoGraeca<\/a> has added a photo to the pool:<\/p> <p><a href=\"http://www.flickr.com/photos/testudograeca/3762164698/\" title=\"Schildkröten_2009\"><img src=\"http://farm3.static.flickr.com/2573/3762164698_6f27527c81_m.jpg\" width=\"240\" height=\"166\" alt=\"Schildkröten_2009\" /><\/a><\/p> <p><a href=\"http://www.testudograeca.de\" rel=\"nofollow\">www.testudograeca.de<\/a><\/p>",
                        "published": "2009-07-27T13:57:24Z",
                        "author": "nobody@flickr.com (TestudoGraeca)",
                        "author_id": "27736205@N04",
                        "tags": "shop online info terrarium heizung schildkröte warstein schildkröten gehege türkische ibera photovoltaik testudograeca landschildkröte frühbeet freigehege quarantäne maurische gartenbeleuchtung winterstarre auswinterung dirkvöllmeke gartengehege schildkrötenunterschlupf pflanzsteine frühbeetheizung danielastockhausen wwwschildkröteonlinede"
           },
...
});

We aren’t finished yet. Did you notice the jsonFlickrFeed( piece at the beginning? That is the function call I wrote about earlier. If we included this as an script in our page, for example like this:

var url = 'http://api.flickr.com/services/feeds/groups_pool.gne?id=78811852@N00&lang=en-us&format=json';
var script = document.createElement("script");
script.setAttribute("src", url);
script.setAttribute("type", "text/javascript");
document.body.appendChild(script);

when the script was loaded, it would execute and call the jsonFlickrFeed function. But the call would fail, because there isn’t any function with that name.

This is why the callback parameter is used in the URL. Let’s say you have a function like this:

function jsonphandler(data)
{
        alert("hey! jsonphandler was called ");
        // do something with data
}

If we append jsoncallback=jsonphandler to the previous pool URL, the response will begin with jsonphandler( instead of jsonFlickrFeed(, and our own function (i.e., jsonphandler) will be called when the script is loaded.

To sum things up: JSONP is all about loading a new SCRIPT element, which calls a function that you have specified beforehand. It still needs a cooperating server in order to work, but since SCRIPT tags aren’t subject to the same cross domain restrictions as XMLHttpRequest calls (AJAX for buzz words lovers), this is the only solution you have if you want to pull data from a different domain without using a proxy.

A word of caution, though: unlike simple RSS retrievals, this actually allows the remote server to inject any javascript code they wish in your page, because you’re liberally loading whatever they return to you. A malicious server could return other javascript code instead of the simple function call you expect. Therefore, you should use this only with servers you can really trust.

Reasons for using UTF-8

The subject on encoding is quite confusing and at the beginning one does never really know what are the differences between encoding types, and most importantly, what are the consequences of choosing ISO-8859 instead of UTF-8, so now that I begin to have more arguments than the Trust me, I think this is the right decision one, I want to share with you what I know – and of course, please correct me where I am wrong!

The main problem is the development platform, which happens to be Windows most of the times – and its default encoding, which seems to be ISO-8859. Since the majority of web developers are in countries which have more than enough with ISO-8859 (Europe, North America, etc…), and that majority also tend to use Windows, their servers are set to use ISO-8859, the databases are created using ISO-8859, and the code and templates and by extension the pages come out automatically with ISO-8859 (although I have also noticed that Eclipse sets the default encoding to CP-1252, in every platform – which is something that keeps puzzling me!).

It is fine if you don’t expect to have any non ISO-8859 in your content ever, but that only happens in very specific cases – and often you are the only person entering content. But most of the websites you build will probably allow people from all around the world to register and submit their content, and here’s where the fun begins:

  1. Even if the site is in English, people’s names are still in their own language. Let them enter their name with their characters and don’t force them to pseudotranslate them into English. Obviously, the name is just an example. It could also be book and movie titles, or music albums, etc…
  2. If you aggregate feeds from other sites, they most probably will come in UTF-8. If your site is not in UTF-8, you’ll have to either use utf8_decode (in php) or convert that text into html entities.
  3. If you use Flash with dynamic content (which you generate), it will expect the content to show up encoded in UTF-8. There’s no way of changing that unless you mess around with the evil systemCodepage setting (but that’s a bad idea)
  4. If you use AJAX, you need to return UTF-8 content. Just like the Flash case
  5. If you expect to use the content of your non-UTF-8 website in other applications which do support UTF-8 (for example, a reports system) but are not web based and you used the html entities trick for storing UTF-8 content in your database, you’ll have to convert back the html entities into UTF-8 or sort of it (and fingers crossed!)

Considering all the above situations, it’s easy to see that it’s better to use UTF-8 straight on from the beginning.

In that case:

  1. People can register using their normal name. Japanese people (for example) will be happy.
  2. Aggregate everything you want and don’t worry about external feeds having characters that your page encoding doesn’t include
  3. Flash will be happy. Now you just need to make sure to embed all the characters you may need – but that’s another story
  4. AJAX will be happy too
  5. Generate reports without having to mess with html entities. What you query is what you need.

… and the best of all is that as long as your system is properly set up, you don’t need to do anything special about UTF-8 in your code. You just need to think about the content, and stop worrying about utf8_encode’s or utf8_decode’s, htmlentities and all that mess!

Did I convince you to use UTF-8?

Egosearch-ing

A bit not too useful at first sight but proves how powerful can be an ajax powered search engine. As I understand, this looks for the query string you give, related to the url’s you provide, and then returns you a number of ego points. For example, this is the result of searching for Soledad Penades and www.soledadpenades.com. Of course, the most ego points you have, the more your ego grows (or the more pages are linking to your pages, in other words).

And it has a very nice implementation… works fabulously with Safari (which is not quite often with most of the ajax applications I have seen to date).

Have a try! Ego surf!

(Found via ajaxian)