Salve a tutti, da non molto tempo mi sto cimentando con ajax, e nello studiare alcuni script sono arrivato al punto del passaggio di parametri tra un file html e un file php il tutto gestito da ajax, riporto qui di sseguito gli script in html, js, e php, i file in tutto sono 4 in quanto php effettua sia la gestione dei parametri raccolti dal file html, che la gestione degli errori, in ultimo php passa al file html il risultato in xml, riporto qui di seguito i file:
1) morephp.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<title>Ajax : il passaggio di parametri e la gestione di errori</title>
<script type="text/javascript" src="morephp.js"></script>
</head>
<body>
Chiediamo al server di dividere
<input type="text" id="firstNumber" />
per
<input type="text" id="secondNumber" />
<input type="button" value="Send" onclick="process()" />
<div id="myDivElement"/>
</body>
</html>
2) morephp.js
//l'istanza XMLHttpRequest
//creo l'istanza dell'oggetto XMLHttpRequest
var xmlHttp = createXMLHttpRequestObject();
function createXMLHttpRequestObject()
{
//memorizza il riferimento dell'oggetto XMLHttpRequest
var xmlHttp;
//x tutti i browser eccetto IE6
try
{
xmlHttp = new XMLHttpRequest();
}
catch( e )
{
var xmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",
"MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0","MSXML2.XMLHTTP.3.0",
"MSXML2.XMLHTTP","Microsoft.XMLHTTP");
//adesso provo tutti gli elementi dell'array finchč nn ne trovo quello giusto
for (var i=0; i < xmlHttpVersions.length && !xmlHttp; i ++)
{
try
{
xmlHttp = new ActivexObject(xmlHttpVersions[i]);
}
catch( e ) {}
}
}
if( !xmlHttp )
alert("Err!!!!! during the creation XMLHttpRequestObject");
else
return xmlHttp;
}
function process()
{
if( xmlHttp )
{
try
{
xmlHttp.open('GET', 'morephp.php?',+ params, true );
xmlHttp.onreadystatechange = handleRequestStateChange;
xmlHttp.send( null );
}
catch( e )
{
alert("Err!!!! collegamento al server:\n" +e.toString());
}
}
}
function handleServerReponse()
{
var xmlResponse = xmlHttp.responseXML;
//cattriamo eventuali erroricon firefox
//valutiamo eventuali errori con opera e ie6
if (!xmlResponse || !xmlResponse.DocumentElement )
throw ("Struttura XML non valida:\n" + xmlHttp.ResponseText );
//catturiamo eventuali errori
var rootNodeName = xmlResponse.documentElement.nodeName;
if (rootNodeName == "parsererror") throw ("Strutt XML non vaslida(12)");
//otteniamo il documento radice dal file xml
xmlRoot = xmlResponse.documentElement;
//otteniamo gli array con i titoli dei libri e tutti gli altri dati
titleArray = xmlRoot.getElementsByTagName("title");
isbnArray = xmlRoot.getElementsByTagName("isbn");
//output HTML
var html="";
//iterazione degli elementi per l'output hml
for(var i=0; titleArray.length; i++)
html += titleArray.item( i ).firstChild.data +", "+isbnArray.item( i ).firstChild.data +"
";
// otteniamo un riferimento all'elemento <div> della pagina
myDiv = document.getElementById ("myDivElement");
//mostriamo l'output in html
myDiv.innerHtml = html;
}
function handleRequestStateChange()
{
//quando readystate č in posizione 4 siamo pronti per leggere la risposta
if (xmlHttp.readyState == 4)
{
if (xmlHttp.status == 200)//TEST
{
try
{
handleServerResponse();
}
catch( e )
{
alert("errore durante la lettura della risposta:"+ e.toString());
}
}
else
{
alert('Si sta verificando un errore sul server nella ricezione dei dati:\n'+ xmlHttp.StatusText );
}
}
}
//gestione risposta ricevuta dal server
function handleServerResponse()
{
//recupera la risposta del server sotto forma di oggetto XML
DOM var xmlResponse = xmlHttp.responseXML ;
// catturiamo eventuali errori con IE e Opera
if (!xmlResponse || !xmlResponse.documentElement )
throw("Struttura xml non valida:\n" + xmlHttp.responseText );
//catturiamo eventuali errori con ff
if (rootNodeName == "parsererror")
throw("Struttura xml non valida:\n" + xmlHttp.responseText );
//IL VALORE CHE DOBBIAMO MOSTRARE Č IL FIGLIO DELL'ELEMENTO ROOT DI RESPONSR
responseText = xmlRoot.firstChild.data;
//mostriamo il messaggio all'utente
myDiv = document.getElementById("myDivElement");
myDiv.innetHTML = "il server dice che la risposta č:" + reponseText;
}
3) morephp.php
<?php
//carichiamo il modulo per la gestione degli errori
require_once('error_handler.php');
//inviamo l'output come xml
header ('Content-Type: text/xml');
//calcoliamo il risultato
$firstNumber = $_GET['firstNumber'];
$secondNumber = $_GET['secondNumber'];
$result = $firstNumber / $secondNumber;
//creiamo il nuovo documento XML
$dom = new DOMDocument();
//creiamo l'elemento radice response
$response = $dom -> createElement('response');
$dom -> appendChild($response);
// aggiungiamo l'elemento calcolato al response
$responseText = $dom ->createTexNode($result);
$response -> appendChild($responseText);
//costruiamo la struttura XML in una variabile stringa
$xmlString = $dom -> saveXML(); //N.B.
//restituiamo la variabile stringa
echo $xmlString;
?>
4) error_handler.php
<?php
//impostiamo error_handler come metodo per la gestione degli errori
set_error_handler('error_handler', E_ALL);
//funzione per la gestione degli errori
function error_handler($errNo, $errStr, $errFile, $errLine)
{
//cancelliamo qualunque output che č stato generato
if(ob_get_length()) od_clean();
//restituiamo il messaggio di errore
$error_message = 'ERRNO:' . $errNo.chr(10). 'TEXT:'. $errStr.chr(10). 'LOCATION:' . $errFile . ', line' . $errLine;
echo $error_message;
//evitiamo che venga processato il resto dello script PHP
exit;
}
?>
Solo che testando i file su firefox, nn ho alcun risultato e vedendo la console degli errori mi da come messaggi di errore :
1) process is not definided in morephp.html
2) missing ; in DOM var xmlResponse = xmlHttp.responseXML; al file morephp.js :master:
Qualcuno di voi sā dirmi dove ho sbagliato????