2011-06-16 32 views
6

Deseo aplicar "Jquery UI Autocompletar con valores múltiples" a un campo de entrada de formularios de registro.Autocompletar no funciona correctamente

Lo que quiero hacer exactamente: Cuando el visitante escribe el nombre del usuario existente en este campo de entrada, antes que nada, el script busca la existencia del nombre, lo completa (si existe), agrega una coma. El usuario puede escribir el segundo, el tercer nombre de usuario existente en este campo y el script cada vez que se complete automáticamente. Y cuando el visitante hace clic para enviar el botón, PHP busca los id de estos nombres de usuario, crea una matriz de identificadores y los agrega a los nuevos usuarios del campo "amigos" en la tabla db.

Mi código:

HTML

<form action="index.php" method="post">  
<input class="std" type="text" name="friends" id="friends"/> 
<input type="submit" name="submit"> 
</form> 

Jquery

$(function() { 
    function split(val) { 
     return val.split(/,\s*/); 
    } 
    function extractLast(term) { 
     return split(term ).pop(); 
    } 

    $("#friends") 
     // don't navigate away from the field on tab when selecting an item 
     .bind("keydown", function(event) { 
      if (event.keyCode === $.ui.keyCode.TAB && 
        $(this).data("autocomplete").menu.active) { 
       event.preventDefault(); 
      } 
     }) 
     .autocomplete({ 
      source: function(request, response) { 
       $.getJSON("search.php", { 
        term: extractLast(request.term) 
       }, response); 
      }, 
      search: function() { 
       // custom minLength 
       var term = extractLast(this.value); 
       if (term.length < 2) { 
        return false; 
       } 
      }, 
      focus: function() { 
       // prevent value inserted on focus 
       return false; 
      }, 
      select: function(event, ui) { 
       var terms = split(this.value); 
       // remove the current input 
       terms.pop(); 
       // add the selected item 
       terms.push(ui.item.value); 
       // add placeholder to get the comma-and-space at the end 
       terms.push(""); 
       this.value = terms.join(", "); 
       return false; 
      } 
     }); 
}); 

este archivo PHP es original de la carpeta de muestra, que funciona a la perfección. pero yo quiero ir a buscar la base de datos en lugar de la matriz
original search.php

$q = strtolower($_GET["term"]); 
if (!$q) return; 
$items = array(
"Great Bittern"=>"Botaurus stellaris", 
"Little Grebe"=>"Tachybaptus ruficollis", 
"Black-necked Grebe"=>"Podiceps nigricollis", 
"Little Bittern"=>"Ixobrychus minutus", 
"Black-crowned Night Heron"=>"Nycticorax nycticorax", 
"Purple Heron"=>"Ardea purpurea", 
"White Stork"=>"Ciconia ciconia", 
"Spoonbill"=>"Platalea leucorodia", 
"Red-crested Pochard"=>"Netta rufina", 
"Common Eider"=>"Somateria mollissima", 
"Red Kite"=>"Milvus milvus", 

); 

function array_to_json($array){ 

    if(!is_array($array)){ 
     return false; 
    } 

    $associative = count(array_diff(array_keys($array), array_keys(array_keys($array)))); 
    if($associative){ 

     $construct = array(); 
     foreach($array as $key => $value){ 

      // We first copy each key/value pair into a staging array, 
      // formatting each key and value properly as we go. 

      // Format the key: 
      if(is_numeric($key)){ 
       $key = "key_$key"; 
      } 
      $key = "\"".addslashes($key)."\""; 

      // Format the value: 
      if(is_array($value)){ 
       $value = array_to_json($value); 
      } else if(!is_numeric($value) || is_string($value)){ 
       $value = "\"".addslashes($value)."\""; 
      } 

      // Add to staging array: 
      $construct[] = "$key: $value"; 
     } 

     // Then we collapse the staging array into the JSON form: 
     $result = "{ " . implode(", ", $construct) . " }"; 

    } else { // If the array is a vector (not associative): 

     $construct = array(); 
     foreach($array as $value){ 

      // Format the value: 
      if(is_array($value)){ 
       $value = array_to_json($value); 
      } else if(!is_numeric($value) || is_string($value)){ 
       $value = "'".addslashes($value)."'"; 
      } 

      // Add to staging array: 
      $construct[] = $value; 
     } 

     // Then we collapse the staging array into the JSON form: 
     $result = "[ " . implode(", ", $construct) . " ]"; 
    } 

    return $result; 
} 

$result = array(); 
foreach ($items as $key=>$value) { 
    if (strpos(strtolower($key), $q) !== false) { 
     array_push($result, array("id"=>$value, "label"=>$key, "value" => strip_tags($key))); 
    } 
    if (count($result) > 11) 
     break; 
} 
echo array_to_json($result); 

search.php Cambiado

$conn = mysql_connect("localhost", "tural", "0579ural") or die(mysql_error());; 
mysql_select_db("askon", $conn) or die(mysql_error());; 
$q = strtolower($_GET["term"]); 
if (!$q) return; 
$query = mysql_query("select id, fullname from usr_table where fullname like '$q%'") or die(mysql_error());; 
$results = array(); 
while ($row = mysql_fetch_array($query)) { 
    $results[] = array($row[1] => $row[0]); 
} 
echo json_encode($results); 

autocompletar script PHP funciona prntscr.com/22mxl, pero creo que algo malo con jQuery : no muestra el menú. prntscr.com/22mxg. ¿Cómo resolver este problema? P.S PARA BÚSQUEDA ORIGINAL .PHP DEVOLVERÁ algo así como prntscr.com/22n0e y muestra prntscr.com/22n0r.

+0

creo que necesitas json_encode ($ resultados [0]); check in firebug la respuesta estás recibiendo cualquier respuesta o nada en absoluto. –

+0

no. search.php funciona correctamente. Debería cambiar algo en jquery. por favor abra capturas de pantalla y verá la diferencia entre el archivo original y el –

+0

en su javascript do console.log (this.value) dentro de la función de selección –

Respuesta

Cuestiones relacionadas