Foros del Web » Programando para Internet » Javascript » Frameworks JS »

Autocompletar

Estas en el tema de Autocompletar en el foro de Frameworks JS en Foros del Web. Hola a todos. Estoy empezando a programar algo en ajax, necesito un formulario con un campo de texto que se autorrellene al ir escribiendo en ...
  #1 (permalink)  
Antiguo 25/10/2010, 04:51
Avatar de aalleexx81  
Fecha de Ingreso: noviembre-2009
Mensajes: 153
Antigüedad: 14 años, 5 meses
Puntos: 0
Pregunta Autocompletar

Hola a todos. Estoy empezando a programar algo en ajax, necesito un formulario con un campo de texto que se autorrellene al ir escribiendo en él.
Tengo una base de datos con una tabla usuarios con los campos iduser, nombre, apellido1 y apellido2. Cuando el usuario introduzca el apellido quiero que aparezca el desplegable con: <iduser> nombre apellido1 apellido2 en este mismo formato.

La cosa es que no consigo hacer que funcione:

os facilito los códigos que estoy usando:

rpc.php

<?php

// PHP5 Implementation - uses MySQLi.
// mysqli('localhost', 'yourUsername', 'yourPassword', 'yourDatabase');
$db = new mysqli('localhost', 'root' ,'', 'heraclesprueba');

if(!$db) {
// Show error if we cannot connect.
echo 'ERROR: Could not connect to the database.';
} else {
// Is there a posted query string?
if(isset($_POST['queryString'])) {
$queryString = $db->real_escape_string($_POST['queryString']);

// Is the string length greater than 0?

if(strlen($queryString) >0) {
// Run the query: We use LIKE '$queryString%'
// The percentage sign is a wild-card, in my example of countries it works like this...
// $queryString = 'Uni';
// Returned data = 'United States, United Kindom';

// YOU NEED TO ALTER THE QUERY TO MATCH YOUR DATABASE.
// eg: SELECT yourColumnName FROM countries WHERE value LIKE '$queryString%' LIMIT 10

$query = $db->query("SELECT iduser, nombre, apellido1, apellido2 FROM usuarios WHERE apellido1 LIKE '$queryString%' LIMIT 10");
if($query) {
// While there are results loop through them - fetching an Object (i like PHP5 btw!).
while ($result = $query ->fetch_object()) {
// Format the results, im using <li> for the list, you can change it.
// The onClick function fills the textbox with the result.

// YOU MUST CHANGE: $result->value to $result->your_colum
echo '<li onClick="fill(\''.$result->value.'\');">'.$result->value.'</li>';
}
} else {
echo 'ERROR: There was a problem with the query.';
}
} else {
// Dont do anything.
} // There is a queryString.
} else {
echo 'There should be no direct access to this script!';
}
}
?>


index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax Auto Suggest</title>

<script type="text/javascript" src="jquery-1.2.1.pack.js"></script>
<script type="text/javascript">
function lookup(inputString) {
if(inputString.length == 0) {
// Hide the suggestion box.
$('#suggestions').hide();
} else {
$.post("rpc.php", {queryString: ""+inputString+""}, function(data){
if(data.length >0) {
$('#suggestions').show();
$('#autoSuggestionsList').html(data);
}
});
}
} // lookup

function fill(thisValue) {
$('#inputString').val(thisValue);
setTimeout("$('#suggestions').hide();", 200);
}
</script>

<style type="text/css">
body {
font-family: Helvetica;
font-size: 11px;
color: #000;
}

h3 {
margin: 0px;
padding: 0px;
}

.suggestionsBox {
position: relative;
left: 30px;
margin: 10px 0px 0px 0px;
width: 200px;
background-color: #212427;
-moz-border-radius: 7px;
-webkit-border-radius: 7px;
border: 2px solid #000;
color: #fff;
}

.suggestionList {
margin: 0px;
padding: 0px;
}

.suggestionList li {

margin: 0px 0px 3px 0px;
padding: 3px;
cursor: pointer;
}

.suggestionList li:hover {
background-color: #659CD8;
}
</style>

</head>

<body>


<div>
<form>
<div>
Intruce usuario:
<br />
<input type="text" size="30" value="" id="inputString" onkeyup="lookup(this.value);" onblur="fill();" />
</div>

<div class="suggestionsBox" id="suggestions" style="display: none;">
<img src="upArrow.png" style="position: relative; top: -12px; left: 30px;" alt="upArrow" />
<div class="suggestionList" id="autoSuggestionsList">
&nbsp;
</div>
</div>
</form>
</div>

</body>
</html>

Al haber tuneado un código de internet creo que es importante que os comente que tengo un fichero en ajax que no hay quien lo entienda con muchos símbolos.

Creo que la consulta está bien, ya que cuando introduzco un apellido existente en la base de datos, el desplegable sale pero sin nada dentro, incluso puedo seleccionar algo que aparentemente está dentro pero al clickar con el mouse no se introduce absolutamente nada en el campo de texto.

Os agradecería que me echarais una mano, porque llevo toda la semana liado con esto y no hay forma. Estoy a punto de abandonar.

Un cordial saludo.

Etiquetas: ajax, autocompletado
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 10:41.