Ver Mensaje Individual
  #3 (permalink)  
Antiguo 10/10/2012, 08:09
Avatar de ivanin87
ivanin87
 
Fecha de Ingreso: marzo-2008
Mensajes: 77
Antigüedad: 16 años
Puntos: 0
Respuesta: Problema formulario Ajax

Aunque hace que no escriba por aquí, he solucionado este tema que tenía pendiente, pero me ha creado otro problema. Cuando empiezo a escribir empieza a buscar correctamente las coincidencias y mientras siga escribiendo esa palabra todo va bien, el caso es que cuando meto un caracter diferente la consulta no se modifica y por tanto la opción no desaparece. Como es un poco lio pongo un ejemplo:

Tengo un campo Habilidad y en la tabla habilidades de la BBDD (donde busca las coincidencias) solo tengo un registro que es "Deporte". Si voy escribiendo la palabra Deporte va saliendo perfectamente pero si cuando llevo escrito Dep, pongo una "a" por ejemplo, la opción no desaparece pese a que "Depa" no es parte de la palabra "Deporte". En cambio si borro todos los caracteres y dejo el text vacío sí que desaparece el cuadro de opciones.

El código es el siguiente:
SCRIPT
Código PHP:
function lookup(inputString) {
        if(
inputString.length == 0) {
            
// Hide the suggestion box.
            
$('#suggestions').hide();
        } else {
            $.
post("habilidades.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);
    } 
PARTE CORRESPONDIENTE DEL INDEX
Código PHP:
<div style="width:600px;margin-top:2px;">
                <
div style="width:150px; float:left; margin-top:5px;"><span style="color:#84A412">*</span>Habilidades:</div>
                <
input type="text" size="30" value="" id="inputString" onkeyup="lookup(this.value);" onblur="fill();" name="habilidades" style="width:200px;" />
                <
input type="submit" name="insertarHabilidad" value="Insertar Habilidad" style="width:150px;" />
            </
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
HABILIDADES.PHP (Lo llama el Script)
Código PHP:
<?php
    
    
// PHP5 Implementation - uses MySQLi.
    // mysqli('localhost', 'yourUsername', 'yourPassword', 'yourDatabase');
    
$db = new mysqli('localhost''root' ,'''registro');
    function 
limpiarString($string//función para limpiar strings
    
{
        
$string strip_tags($string);
        
$string htmlentities($string);
        return 
stripslashes($string);  
    }
    
    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 yourTable WHERE yourColumnName LIKE '$queryString%' LIMIT 10
                
                
$query $db->query("SELECT DISTINCT habilidad FROM habilidades WHERE habilidad 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(\''.limpiarString($result->habilidad).'\');">'.limpiarString($result->habilidad).'</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!';
        }
    }
?>