Juzaam the WEBlacksmith

How to correctly manage entities in a AJAX form and avoid strange chars

di Juzaam del mag.03, 2009, nella sezione I consigli dello zio Juz, Mootools, PHP, jQuery

I struggled for days to understand a very common and googled problem: how to correctly manage entities when sending an AJAX form.

Problem : after sending a form via Mootools , I’m getting weird characters instead (? or strange As) of normal entities like à è é ì ò ù and so on. Also, these characters fill again those inputs and textareas from which they come from, creating an infernal loop of strange characters multiplication…

Explanation: XML can only handle UTF-8 charset and, for what I could appreciate, both jQuery and Mootools UTF-encode all data sent / received via an AJAX request, no matter what type of encoding you specify inside the request. So the loop is :

INPUT DATA -> à -> SEND-> A’? (utf encoded , weird) -> INPUT RELOAD (with A’?) -> SEND AGAIN -> A’?A’? (utf double-encoded , even weirder!)

Solution: after trying the strangest and weirdest solution , i finally found the appropriate one : PHP utf8_decode($value) function executed after receiving data from an AJAX request and before storing this data in a MySQL table, for example.
THE most important part is that you have to differenciate between a situation when your  form is sent “traditionally”, using the submit button, and when you send it using AJAX, for example if you want to save temporary data before actually sending the form.

A nice trick is using a normal $_GET variable in your js code , to tell your PHP script that you are sending from AJAX.

Ex: (Mootools)

       // After clicking "link" , we want our form to be sent to the script specified in his
      // action attribute, sending also the variable ajax = 1 via $_GET

       link.addEvent('click',function(){
			$('form_report').send( $('form_report').get('action') + '&ajax=1' );
	});

On PHP side :

// We decode every and each value sent via POST
 foreach ($_POST as $key=>$value){
   if (@$_GET['ajax']) $_POST[$key] = utf8_decode($value);
}

This way you are safe either you are sending your form via HTML or AJAX.

If you ever need to decode this data on Javascript, I suggest you use the Javascript equivalent for PHP functions by Kevin van Zonneveld, which basically provide PHP functions inside Javascript, utf_decode() included ;-)

Comments :, altro...

How to submit a HTML form via AJAX using jQuery

di Juzaam del apr.30, 2009, nella sezione I consigli dello zio Juz, jQuery

I started learning jQuery, since I feel that MooTools is getting inadequate.

Here is a short example on how to submit a form using AJAX in jQuery:

<script type="text/javascript">
$(document).ready(function(){
    // $(':input') allows to select all fields inside our form and send with the post event
    // In this case we also want to get back the response from submit.php.
    // We also want to wrap our submission in a function to eventually call it from other scenarios
    function form_submit(){
       $.post($("#myForm").attr("action"),  $(':input'),
                function(response){
                    alert("Response: " + response);
       });
    }

    // Grabbing the submit event
     $("#myForm").submit(function() {
      form_submit();
    });
});

</script>

<form id="myForm" action="submit.php">
Value 1: <input name="input1" type="text" /><br />
Value 2: <input name="input2" type="text" /><br />
<input type="submit" value="Submit!" />
</form>
Comments altro...

Dregister v.1.3 released

di Juzaam del feb.14, 2009, nella sezione WordPress

I just released a new version of Dregister plugin , 1.3.

New features:

  • “Radio” type custom field. A.K.A. multiple choice answer
  • Lighter AJAX administration. (the power of JSON Request , I’ll write something about MooTools + JSON soon)

Visit the official WP page for download. screenshot-1

Comments :, , , , altro...

Wordpress 2.7.1 and error 500

di Juzaam del feb.11, 2009, nella sezione I consigli dello zio Juz, WordPress

If you have just upgraded WordPress to the last version and got a nice “Error 500” : don’t worry!

All you have to do is to set your permissions back to 755 via your favourite FTP client.
This is usually done right-clicking on a directory and choosing “Properties / CHMOD

Comments :, , altro...

Niente di vero .. tranne gli occhi

di Juzaam del feb.10, 2009, nella sezione Life

Ho sempre odiato i reality. Per me non fa differenza che ci siano di mezzo le talpe, gli scoiattoli, i fratelli, gli zii o i cromosomi X.
Li odio soprattutto perché , quasi a prendersi in giro da soli, mostrano sempre il loro lato più falso.

Di tanto in tanto, però, l’osservatore attento qualcosa di vero la trova. Che spesso non parla..

Il mio modestissimo tributo a un fotogramma “volante” catturato da YouTube. Vero e meraviglioso..

blueyes

Comments altro...

Windows 7 Beta : primo incontro

di Juzaam del feb.06, 2009, nella sezione I consigli dello zio Juz, Life

Stamattina io e Vista proprio non ce l’abbiamo fatta più. La nostra non è mai stata una unione felice.windows7
Ti avevo scelta perché  mi eri stato regalata dalla Sony. E a caval donato non si guarda in bocca.. Ma tu mi hai vomitato di sopra!

Oggi ti ho tradita. Ed è molto più giovane di te..

Windows 7 è ancora versione Beta, mezza calzetta e così via.  E’ un rischio, una follia da innamorati utilizzarlo per uno sviluppatore che sicuramente non può permettersi di perdere dati/tempo. Ma chissenefrega..

Pare che il team Microsoft si sia dovuto dividere in due quando si è trattato di scegliere il nuovo destino di Windows. E chissà che non se le siano date di santa ragione tra i team di Vista e di W7 , magari dopo aver visto che aborto di mercato è risultato essere l’erede del fortunatissimo XP.

L’installazione è durata circa 20 minuti, previo backup e formattazione. E’ stato del tutto indolore anche per l’abitudine consolidata di tenere il sistema operativo in una partizione e i miei dati in un’altra, lontani come superman dalla kryptonite..

Apache, PHP, MySQL, Firefox, Safari, Thunderbird, Messenger, Avira antivirus , Winamp. Oh raga’, funziona tutto..e senza battere ciglio.

Windows update è stato così gentile da installarmi tutti i drivers audio / video senza chiedere la mia collaborazione, così come ha fatto per la scheda di Rete.

Se cercate grandi cambiamenti estetici, forse rimarrete delusi. L’aspetto è pressocché identico a quello di Vista, tranne per una gestione più intelligente del menu avvio. La cosa più importante, però, è che amenonmeneèmaifregatonulla dell’estetica…  Ma questo Windows 7 Beta mi sta creando molti meno problemi (zero !) delll’ ex- Vista con service pack e amenità varie.
So che dirlo di un prodotto Microsoft , specie in versione Beta, odora di bestemmia, ma fin’ora sembra tutto molto stabile…

Volete provarlo e farvi un’idea ?

  1. Fate un backup minuzioso di TUTTI  i vostri dati (desktop, segnalibri, mails compresi) su un Hard Disk esterno bello capiente
  2. Scaricate la versione beta gratuita : http://www.microsoft.com/windows/windows-7/beta-download.aspx
  3. Masterizzate un DVD a partire dal file .iso , magari con un bel programma gratuito come CdBurnerXP
  4. Riavviate il sistema con il DVD inserito e FORMATTATE la partizione dove volete installarlo. Evitate procedure di aggiornamento, andate per l’installazione ex- novo..

Qui dal pianeta Seven passo e chiudo!

P.S. vi tengo aggiornati…

Comments :, , , , , , altro...

My first open WordPress Plugin

di Juzaam del gen.18, 2009, nella sezione Mootools, PHP, WordPress

Someone once said “Best things in life are free” .

I totally agree ;-)
Here is my effort to make WordPress a better place : Dr. Register !

With this plugin I wanted to provide a few, basic features to help user registration be more complete. Plus, I really needed those features for the new SISMPA 2.0 , so I decided to build them on my own ;-)

You can visit the official download page here.

You can send your translation (.po and .mo files) to webmaster [at] juzaam.com . It will be included in next releases and you’ll receive credit for that.

You can suggest future features at http://wordpress.org/tags/dregister

Comments :, , , , altro...

Come scaricare la posta dalla propria webmail a Thunderbird con FreePOPs

di Juzaam del gen.17, 2009, nella sezione I consigli dello zio Juz

Questa notte ho deciso di non dormire. Non è la prima volta in effetti..
Ormai sono mesi che rimando anche di riordinare la stanza. In compenso, stanotte ho deciso di ri-ordinare la posta. E quando dico la posta, intendo TUTTA la posta…

Malauguratamente, tra le varie caselle avute nel corso degli anni, anch’io ho fatto l’errore di aprirne una su tin.it. Se qualcuno ha provato l’esperienza, saprà che da un po’ di tempo non è più possibile scaricarsi la posta su Thunderbird (o Outlook), a meno di pagare qualcosina. Stessa cosa per le caselle libero.it, hotmail e via dicendo.

E io non me l’accollo. Oggi vi spiego come usare un magnifico programma , FreePOPs , e riappropriarvi della vostra posta per non restituirla mai più. E chissà, magari per spostarvi su GMAIL ;)

Cominciamo :

  1. Scaricate il piccolo programma a questo indirizzo : http://www.freepops.org/en/download.shtml
  2. Installatelo
  3. [WINDOWS] andate su START -> Programmi -> FreePOPS -> Service -> Install service (default options)
  4. [WINDOWS] andate su START -> Programmi -> FreePOPS -> FreePOPS
  5. Aprite Thunderbird
  6. Andate su File -> Nuovo -> Account
  7. Scegliete “Account di Posta”  e andate avanti
  8. Digitate il vostro nome e il vostro indirizzo e-mail completo, e avanti
  9. Lasciate selezionato POP e alla voce Server in ingresso scrivete i dati del POP del vostro provider.
    Se non sapete quale sia il vostro (o non sapete cos’è un pop) , date un’occhiata a questa pagina . Cercate il vostro provider di posta nella colonna “Provider Fornitore” e copiate l’indirizzo corrispondente alla colonna “POP3” . Poi incollatelo su Thunderbird nel campo in questione
  10. Deselezionate  “Usa Posta in arrivo globale (posta nelle Cartelle Locali)” per tenere ben separate le nuove e-mail da quelle di eventuali altri account. Andate avanti
  11. Alla voce “Nome utente posta in entrata” scrivete il vostro indirizzo e-mail completo (es lanzaezio@virgilio.it). Avanti!
  12. Alla voce “Nome account” , scrivete quel che vi pare : P Avanti!
  13. Deselezionate la voce “Scarica subito i messaggi” che non abbiamo ancora finito…. Cliccate su Fine.
  14. Andate su Strumenti -> Impostazioni Account
  15. Selezionate la voce “Impostazioni Server” relativa all’account appena creato. Alla voce “Nome server” scrivete localhost , alla voce “Porta” scrivete 2000 . Lasciate il resto invariato.
  16. FINE! Adesso siete pronti a scaricare con thunderbird i messaggi che erano imprigionati nella vostra webmail ;)

Grazie ad Alessio Caprari, Nicola Cocchiaro, Russell Schwager, Enrico Tassi e Simone Vellei per aver sviluppato questo meraviglioso software. Chissà perchè sono sempre gli italiani..

Potete far loro una donazione qui ;)

Comments :, , , , , , , , , , , , altro...

How to chain Ajax requests functions with Mootools 1.2

di Juzaam del dic.22, 2008, nella sezione Mootools

I rather publish this in English than in Italian since I think that this hint could be useful to Mootools programmers Worldwide.

Have you ever found yourself wishing you could time-chain your javascript AJAX requests in Mootools?
That wonderful embedded function “chain()” works only with Fx transitions, unfortunately.

Don’t worry: with a few tricks I’ll teach you how to chain your requests, so that the last one will always be the last to be executed.

Here is the code, below it a short explanation:

window.addEvent('domready',function(){
		// First HTML request
		function request1(onCompleteF){
			var req1 = new Request.HTML(
				{
				url:'myurl1.php',
				data: 'nocache=' + new Date().getTime(),
				onSuccess: function(html){

					if (onCompleteF != null){ onCompleteF(); }

				}
			}).send();
		}

		// Second HTML request
		function request2(onCompleteF){
			var req2 = new Request.HTML(
				{
				url:'myurl2.php',
				data: 'nocache=' + new Date().getTime(),
				onSuccess: function(html){

					if (onCompleteF != null){ onCompleteF(); }

				}
			}).send();
		}	

		// Trigger event
		$('myelement').addEvent('click',function(){

			request1( ( function(){ request2(); } ) ); 

		});

});

Basically we wrap each request inside a function. This wrap function expects the argument “OnCompleteF”, which will be another function exeuted at the and of the OnSuccess Event.
Wrapping every AJAX request inside a function like this will let us specify , via a simple argument in the function call, which function/request we would like to be executed after.

NOTE: inside this example you can see another nice trick to avoid browser caching, the option

data: 'nocache=' + new Date().getTime()"

This creates a magnificent, endless and perfectly timed sequence of triggered functions ;)

Comments :, , , , , , , , altro...

Le meraviglie del Web 2.0

di Juzaam del dic.08, 2008, nella sezione Life

Internet ci salverà , questo è poco ma sicuro…

Ci salverà da più situazioni rispetto a quelle che la nostra povera mente è in grado di immaginare.
Un mio carissimo amico mi ripete sempre ” Senza farci troppo caso, quelli della Sony hanno messo in rete e creato il più potente elaboratore di dati della storia ” … Ovvero le milioni di Playstation 3 vendute in giro per il mondo.

La Rete è di tutti e per tutti. Davanti allo schermo non importa che tu sia Barack Obama o il panettiere sotto casa. La Rete è l’unico strumento democratico mai creato dall’uomo.

Il perchè di tutte ste fregnacce? L’ennesimo collaudo di “connettività” … Scrivere sul proprio Blog e automaticamente scrivere anche su Facebook.

Vediamo se funziona…

Comments :, , , , altro...