index.php:
<input type="text" id="nombre">
<div id="resultado"></div>
<script>
document.getElementById("nombre").addEventListener("keyup", function () {
var pepe = new XMLHttpRequest();
pepe.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById('resultado').innerHTML = this.responseText;
console.log(this.responseText);
}
}
var nombre=document.getElementById('nombre').value;
pepe.open("POST", "datos.php");
pepe.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
pepe.send("nombre="+nombre);
})
</script>
datos.php:
<?php
$nombre = filter_input(INPUT_POST, "nombre");
$server = "localhost";
$user = "root";
$password = "";
$db = "sakila";
try {
$conn = new PDO("mysql:host=$server;dbname=$db", $user, $password, [PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"]);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql="select * from actor where first_name like '%$nombre%'";
$res=$conn->query($sql);
$actores=$res->fetchAll();
echo "<actores>";
foreach($actores as $actor){
echo "<actor><first_name>".$actor['first_name'].
"</first_name><last_name>".$actor['last_name'].
"</last_name></actor>";
}
echo "</actores>";
} catch (Exception $ex) {
echo $ex->getMessage();
}