Ejemplo PHP de AJAX
AJAX se utiliza para crear aplicaciones más interactivas.
Ejemplo PHP de AJAX
El siguiente ejemplo demuestra cómo una página web puede comunicarse con un servidor web mientras un usuario escribe caracteres en un campo de entrada:
Ejemplo
Start typing a name in the input field below:
Suggestions:
First name:
Ejemplo explicado
En el ejemplo anterior, cuando un usuario escribe un carácter en el campo de entrada, showHint()
se ejecuta una función llamada.
La función es activada por el onkeyup
evento.
Aquí está el código:
Ejemplo
<p>Start typing a name in the input field below:</p>
<p>Suggestions: <span id="txtHint"></span></p>
<form>
First name: <input type="text" onkeyup="showHint(this.value)">
</form>
<script>
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
document.getElementById("txtHint").innerHTML = this.responseText;
}
xmlhttp.open("GET", "gethint.php?q=" + str);
xmlhttp.send();
}
}
</script>
Explicación del código:
Primero, verifique si el campo de entrada está vacío (str.length == 0). Si es así, borre el contenido del marcador de posición txtHint y salga de la función.
Sin embargo, si el campo de entrada no está vacío, haga lo siguiente:
- Crear un objeto XMLHttpRequest
- Cree la función que se ejecutará cuando la respuesta del servidor esté lista
- Envíe la solicitud a un archivo PHP (gethint.php) en el servidor
- Observe que se agrega el parámetro q gethint.php?q="+str
- La variable str contiene el contenido del campo de entrada.
El archivo PHP - "gethint.php"
El archivo PHP comprueba una serie de nombres y devuelve los nombres correspondientes al navegador:
<?php
// Array with names
$a[] = "Anna";
$a[] = "Brittany";
$a[] = "Cinderella";
$a[] = "Diana";
$a[] = "Eva";
$a[] = "Fiona";
$a[] = "Gunda";
$a[] = "Hege";
$a[] = "Inga";
$a[] = "Johanna";
$a[] = "Kitty";
$a[] = "Linda";
$a[] = "Nina";
$a[] = "Ophelia";
$a[] = "Petunia";
$a[] = "Amanda";
$a[] = "Raquel";
$a[] = "Cindy";
$a[] = "Doris";
$a[] = "Eve";
$a[] = "Evita";
$a[] = "Sunniva";
$a[] = "Tove";
$a[] = "Unni";
$a[] = "Violet";
$a[] = "Liza";
$a[] = "Elizabeth";
$a[] = "Ellen";
$a[] = "Wenche";
$a[] = "Vicky";
// get the q parameter from URL
$q = $_REQUEST["q"];
$hint = "";
// lookup all hints from array if $q is different from ""
if ($q !== "") {
$q = strtolower($q);
$len=strlen($q);
foreach($a as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === "") {
$hint = $name;
} else {
$hint .= ", $name";
}
}
}
}
// Output "no suggestion" if no hint was found or output correct values
echo $hint === "" ? "no suggestion" : $hint;
?>