no... allora senti facciamo un'esempio un pelo più semplice:
(credo che il codice che posto lo capirai senza troppi problemi quindi non l'ho commentato, ma se non capisci qualcosa rispondimi)
1- Crea un file simple_echo.php nella stessa Directory del file della form.
-Testo del file:
<?php
echo $_GET['testo'];
?>
2- Non creare una form (non ne hai bisogno) ma metti solo questo HTML:
Codice PHP:
Metti qui il Testo: <input type="text" name="MyText" id="MyTextId"/>
<input type="button" onclick="getDynamicData('MyTextId')" value="Clicca per Attivare AJAX" />
<div id="MyResultId">
</div>
3- Modifica il JS con questo:
Codice PHP:
function getNewHTTPObject()
{
var xmlhttp;
/** Special IE only code ... */
/*@cc_on
@if (@_jscript_version >= 5)
try
{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (E)
{
xmlhttp = false;
}
}
@else
xmlhttp = false;
@end @*/
/** Every other browser on the planet */
if (!xmlhttp && typeof XMLHttpRequest != 'undefined')
{
try
{
xmlhttp = new XMLHttpRequest();
}
catch (e)
{
xmlhttp = false;
}
}
return xmlhttp;
}
function getDynamicData(id)
{
var text = document.getElementById(id).value;
var xmlHttp = getNewHTTPObject();
var url = "simple_echo.php?testo="+text;
xmlHttp.open('GET', url, true);
xmlHttp.onreadystatechange = callbackFunction;
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.send(null);
}
function callbackFunction()
{
if (this.readyState != 4)
return;
var result = this.responseText;
document.getElementById('MyResultId').innerHTML = result;
}
I punti salienti che vorrei che tu notassi sono:
1- getDynamicData prende ora in ingresso una stringa che utilizza per trovare un elemento che abbia quella stringa come id e ne estragga il contenuto dell'attributo value. Questa funzione viene chiamata sull'evento onClick del bottone nell'HTML e gli viene passato come id l'id dell'input text soprastante.
2- sempre in getDynamicData ho aggiunto la creazione dell'oggetto XMLHttpRequest ( var xmlHttp = getNewHTTPObject()
e come url ho inserito simple_echo.php aggiungendogli come paramentro GET testo= il testo contenuto nell'input text con id passato alla funzione.
3- callbackFunction non si limita ora a controllare che lo stato dell'oggetto XMLHttpRequest sia 4 (concluso con successo) ma anche inserisce come innerHTML del DIV con id="MyResultId" il risultato della chiamata AJAX (che è quello che risponde simple_echo.php).
Una nota: lo Scope della funzione callbackFunction è l'oggetto XMLHttpRequest, quindi puoi accedere al readyState ed al responseText semplicemente usando il this.