Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Friday, 27 May 2011

AJAX and JSON

I recently had to develop a kind of "widget" that interrogates a remote server by means of an asynchronous javascript call. The response was a javascript object defined with JSON syntax. Question was: how do I process it? I found many tutorials that use JSONP techniques (weird yet powerful for cross-site execution) but I don't have control on the remote service. Others suggest an external framework (like jQuery) but I don't like it, I want my own wheel.

So, here come my snippets. First, you make your async call:


xmlhttp = window.XMLHttpRequest?
   new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = parse_function;
xmlhttp.open("GET", service_url );
xmlhttp.send(null);


Then, you handle the response (inside parse_function):


if ( xmlhttp.readyState == 4 && xmlhttp.status == 200) {
   json_data = eval( "(" + xmlhttp.responseText + ")" );
}


This way you get an object filled with usable stuff (json_data). Notice js' eval function and the brackets - those do the trick.

Monday, 28 June 2010

L'usabilità e la scelta del corso di studi

Come sempre in questo periodo, stiamo lavorando alla pubblicazione dell'offerta didattica del prossimo anno accademico. Poichè il nostro ateneo ha una certa grandezza, l'offerta complessiva è decisamente vasta, organizzata in otto facoltà per un totale di circa 70 corsi di laurea differenti, tra triennali, magistrali, UNA specialistica residua (scienze infermieristiche ed ostetriche), "a ciclo unico" e l'ultima vecchio ordinamento (formazione primaria). Non è semplice, per chi visita il sito, orientarsi in questa selva di corsi, e ogni anno si da fondo alla creatività cercando l'organizzazione migliore.

Inoltre, per ragioni storiche, gli studenti tendono a confondere il concetto di "corsi di laurea" e "facoltà". Dai test di usabilità condotti da Stefano lo scorso inverno è emerso che tantissimi visitatori si perdono seguendo i link alle facoltà, credendo di arrivare alle informazioni di un corso di laurea e finendo invece a navigare sui siti satellite. Quest'anno abbiamo riorganizzato completamente la navigazione e tenteremo di frenare questa emorrargia, anche con un motore di ricerca dei corsi di laurea un po' smart.


Conosci il tuo nemico
Partendo dal presupposto che gli studenti non sono tenuti a conoscere l'organizzazione interna dell'Ateneo, abbiamo cercato di rendergli la vita semplice proponendo un motore di ricerca basato sull'elaborazione del testo inserito. Ho cercato di andare oltre il triviale pattern match, perché come detto auspichiamo una certa "tolleranza semantica".

Dunque, uno studente troverà il CdL in "informatica" sia cercando la parola stessa che inserendo "laurea in informatica" o "facoltà di informatica", ma anche cercando altre parole correlate. In sostanza, ho associato ad ogni CdL un insieme di termini che potrebbero essere inseriti dall'utente alla ricerca di quello specifico corso. Naturalmente, le parole di poca rilevanza vengono scartate automaticamente. La ricerca avviene tramite javascript asincrono e quindi in tempo reale senza caricamento.

Una parte interessante è che la complessità insita nell'identificazione del CdL - come sapere a che facoltà afferisce e come si chiama esattamente - viene del tutto mascherata: inserendo brandelli di parole viene generata una lista che potrebbe addirittura suggerire nuovi percorsi agli immatricolandi.

Thursday, 22 April 2010

IE - object does not support property or method

Have you ever experienced the error message I wrote in the title? Are you hitting the walls with your head wondering what the frak it means? This post might be useful to you!

I wrote a page that worked seemlessly inside every know browser but Internet Explorers. Well, nothing new under the sun, web developers' work consists mainly in making things run inside that shit.

Anyway, I was surprised by the nature of the error message: "object does not support property or method", raised during a getElementById call:

foo = document.getElementById("foo");

Element "foo" was a DIV placed in the middle of the page.

So I asked to myself: "what is IE trying to say?". If it really meant that a method wasn't supported, therefore it had to be the getElementById() function, because no other method was involved. But I'm pretty sure that document object HAS a getElementById method. 

The other possibility is the lack of support for the property... but which one? The foo variable?? Yay man! The correct answer is this: you cannot give a variable the name of an element's id. By renaming the variable everything works correctly.

baz = document.getElementById("foo");

Here we go. Do you think this is nonsense? Well, so do I. 

  • First, there's no reason why an HTML element should interfere with javascript variables. 
  • Second, the error raised is totally incomprehensible and misleading. 
  • Third, it's incredible that in 8 versions of IE Microsoft did not think of fixing this.

Monday, 18 January 2010

Deleting stuff with javascript

Would you like to clean house with js without messing around with hidden stuff? Piece of cake:

document.getElementById("thing_to_delete").parentNode.removeChild(document.getElementById("thing_to_delete"));

Yes, it's kinda weird, just like referring to myself as "the son of my father", but it actualy works.

Monday, 8 September 2008

"Cool and quiet" search box

It's cool (and a bit web2.0) to have a search box which works as soon as we cease typing, and displays new contents in the very page we're navigating.

The concept of "typing ceased" is tricky anyway; it's not cool (and not quiet!) to have the page refreshed soon after the onKeyUp event, because maybe we're still typing the whole word.

So, it takes a bit of javascripting:


function lookupStuff(flag) {
if (flag) {
do_things();
} else {
clearTimeout(timerid);
timerid = setTimeout("lookupStuff(true)", 1000);
}
}


If we bind this to the onKeyUp event of an text input form, we have do_things() called after 1 second, which is enough for typing anything; clearing the timer is useful for "jittered" key pressing.

This snippet has been tested successfully on every browser, and appears pretty usable.

Thursday, 4 September 2008

Reload a page with javascript

There's a lot of ways for completely reloading a web page via javascript.

Only a few permit to clean up any selection done to option forms.

Moreover, it turns out that there's only one robust way to do it, without weird confirmations popups (Internet Explorer) or strange behaviours (Firefox):

window.location.href=window.location.pathname;

Of course, works seemlessly in Chrome.