Start!

Server wants to know your name:

Abbiamo dunque bisogno di tre cose:

  • Una pagina HTML (index.html) - si occuperà della vista della nostra applicazione ed avrà il collegamento alla pagina Javascript
  • Una pagina javascript (index.js) - si occuperà di creare l'oggetto per la comunicazione client server e farlo funzionare
  • Una pagina PHP (index.php) - girerà sul server e darà risposte alle nostre domande
index.html
      

<head> <script type="text/javascript" language="javascript" src="index.js"></script> </head> <body onload='process()'> Server wants to know your name: <input type="text" id="myName" /> <div id="divMessage" /> </body>

index.js

// JavaScript Document // contiene il riferimento all'oggetto XMLHttpRequest var xmlHttp = createXmlHttpRequestObject(); // ritrova l'oggetto XMLHttpRequest function createXmlHttpRequestObject() { // contiene il riferimento all'oggetto XMLHttpRequest var xmlHttp; // se il browser è Internet Explorer 6 o più vecchio if(window.ActiveXObject) { try { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { xmlHttp = false; } } // se è Mozilla o altri else { try { xmlHttp = new XMLHttpRequest(); } catch (e) { xmlHttp = false; } } // ritorna l'oggetto o errore if (!xmlHttp) { alert("Error creating the XMLHttpRequest object."); } else { return xmlHttp; } } // fai una chiamata HTTP usando l'oggetto XMLHttpRequest function process() { // verifica che l'oggetto non sia già occupato if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) { // ritrova il nome inserito dall'utente nella form name = encodeURIComponent(document.getElementById("myName").value); // apri una connessione con index.php sul server xmlHttp.open("GET", "index.php?name=" + name, true); // definisci un metodo che gestisca la risposta del server xmlHttp.onreadystatechange = handleServerResponse; // fai la richiesta xmlHttp.send(null); } else { // se la connessione è occupata riprova fra un secondo setTimeout('process()', 1000); } } // funzione di callback eseguita alla risposta del server function handleServerResponse() { // procedi solo se la transazione è conclusa if (xmlHttp.readyState == 4) { //status 200 indica che la transazione è andata a buon fine if (xmlHttp.status == 200) { // recupera l'xml inviato dal server xmlResponse = xmlHttp.responseXML; // ritrova la root del codumento xmlDocumentElement = xmlResponse.documentElement; // recupera il messaggio di testo, primo figlio del nodo root helloMessage = xmlDocumentElement.firstChild.data; // formatta i dati inviati dal server document.getElementById("divMessage").innerHTML = '' + helloMessage + ''; // invia una nuova richiesta setTimeout('process()', 1000); } else { alert("Problem accessing the server: " + xmlHttp.statusText); } } }

index.php

<?php // creeremo dell'XML header('Content-Type: text/xml'); // creiamo l'header echo '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'; // creiamo l'elemento <response> echo '<response>'; // recuperiamo l'user name $name = $_GET['name']; // creiamo un array degli utenti registrati $userNames = array('YODA', 'AUDRA', 'BOGDAN', 'CRISTIAN'); if (in_array(strtoupper($name), $userNames)) { echo 'Hello, master ' . htmlentities($name) . '!'; } else if (trim($name) == '') { echo 'Stranger, please tell me your name!'; } else {
echo htmlentities($name) . ', I don\'t know you!'; } // chiudiamo l'elemento <response> echo '</response>'; ?>