Jump to content


Photo

Autocompletar


  • Please log in to reply
3 replies to this topic

#1 madri09

madri09

    Advanced Member

  • Miembros
  • PipPipPip
  • 72 posts

Posted 26 October 2012 - 05:25 AM

Buenos dias, tengo este autocompletar que he pillado de internet y quisiera ponerle una recuperación de la base de datos con un select.
Como podría hacerlo?


<?php

/*
note:
this is just a static test version using a hard-coded countries array.
normally you would be populating the array out of a database

the returned xml has the following structure
<results>
    <rs>foo</rs>
    <rs>bar</rs>
</results>
*/

    $aUsers = array(
       
        "Zaun, Jillie"
    );
   
   
    $aInfo = array(
        "Bedfordshire"
       
    );
   
   
    $input = strtolower( $_GET['input'] );
    $len = strlen($input);
    $limit = isset($_GET['limit']) ? (int) $_GET['limit'] : 0;
   
   
    $aResults = array();
    $count = 0;
   
    if ($len)
    {
        for ($i=0;$i<count($aUsers);$i++)
        {
            // had to use utf_decode, here
            // not necessary if the results are coming from mysql
            //
            if (strtolower(substr(utf8_decode($aUsers[$i]),0,$len)) == $input)
            {
                $count++;
                $aResults[] = array( "id"=>($i+1) ,"value"=>htmlspecialchars($aUsers[$i]), "info"=>htmlspecialchars($aInfo[$i]) );
            }
           
            if ($limit && $count==$limit)
                break;
        }
    }
   
   
   
   
   
    header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
    header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
    header ("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
    header ("Pragma: no-cache"); // HTTP/1.0
   
   
   
    if (isset($_REQUEST['json']))
    {
        header("Content-Type: application/json");
   
        echo "{\"results\": [";
        $arr = array();
        for ($i=0;$i<count($aResults);$i++)
        {
            $arr[] = "{\"id\": \"".$aResults[$i]['id']."\", \"value\": \"".$aResults[$i]['value']."\", \"info\": \"\"}";
        }
        echo implode(", ", $arr);
        echo "]}";
    }
    else
    {
        header("Content-Type: text/xml");

        echo "<?xml version=\"1.0\" encoding=\"utf-8\" ?><results>";
        for ($i=0;$i<count($aResults);$i++)
        {
            echo "<rs id=\"".$aResults[$i]['id']."\" info=\"".$aResults[$i]['info']."\">".$aResults[$i]['value']."</rs>";
        }
        echo "</results>";
    }
?>


Saludos
  • 0

#2 madri09

madri09

    Advanced Member

  • Miembros
  • PipPipPip
  • 72 posts

Posted 28 October 2012 - 03:28 PM

Compañeros, me he pillado este cod, funciona bien pero el problema es que la recuperación la hace en un listado y yo quiero que la haga en campos de texto independientes.Es decir necesito modificarlo.Os pongo primero un trozo del formulario donde tengo las cajas de texto.En la primera caja llamada teléfono hace la busqueda perfectamente seguidamente en la segunda caja me imprime(apellidos,poblacion,aparato) todos juntos y seguidos como una lista.
Supongo que el que hay que modificar es el ajax.


<div id="wrapper">
      <form action="index_ajax.php" method="get">
          <div class="ausu-suggest">
              <input type="text" size="30" value="" name="telefono" id="telefono" autocomplete="off" />
              <input type="text" size="100" value="" name="apellidos" id="apellidos" autocomplete="off"  />
              <input type="text" size="100" value="" name="poblacion" id="poblacion" autocomplete="off"  />
              <input type="text" size="100" value="" name="aparato" id="aparato" autocomplete="off"  />
          </div>
      </form>



y este el ajax

[js]
(function($){
    $.fn.autosugguest = function(config) {

        var defaults = {
            className: 'suggest',
  methodType: 'POST',
            addParams: null,
              rtnIDs: false,
            dataFile: 'data_ajax.php',
            minChars:  3,
            fadeTime:  100
          };

        var config = $.extend(defaults, config);

        config.addParams = (config.addParams != '') ? '&' + config.addParams : '';

        $('<div class="ausu-suggestionsBox"><img src="images/arrow.png" /><ul></ul></div>').appendTo('.' + config.className);
        $(".ausu-suggestionsBox > ul li").live('mouseover', function()
        {
            var sel = $(this).parent().find("li[class='selected']").removeClass('selected');
                $(this).addClass('selected');
            });

        $("." + config.className + " > input").keyup(function(event)
        {
          var fieldParent = $(this).parents('div.' + config.className);

          if (event.which != 39 && event.which != 37 && event.which != 38 && event.which != 40 && event.which != 13 && event.which != 9 ) {

                fieldVal = fieldParent.find('input:eq(0)').val();
                suggest(fieldVal,this.id);
          } else {

            var fieldChild  = fieldParent.find('.ausu-suggestionsBox > ul');

            switch (event.which)
                {
                case 40: { keyEvent(fieldChild,'next');break; }
                case 38: { keyEvent(fieldChild,'prev');break; }
                case 13:
                {
                        fieldParent.children('input:eq(0)').val($("li[class='selected'] a").text());
                        if (config.rtnIDs==true) fieldParent.children('input:eq(1)').val($("li[class='selected']").attr("id"));
                        fieldParent.children('div.ausu-suggestionsBox').hide();
                        return false;
                        break;
                }
                case 9:
                {
                        offFocus(this); $("li").removeClass("selected");
                        break;
                }
            }
        }
        });

        $("." + config.className).bind("keypress",function(event){
            if (event.keyCode == 13) return false;
        });

        $("." + config.className + " > input").live("blur", function(){ offFocus(this); $("li").removeClass("selected"); });

        function suggest(dataInput, id)
        {
            if(dataInput.length < config.minChars) {
                    $('#'+id).parent('.' + config.className).children('div.ausu-suggestionsBox').fadeOut();
            } else {
            $('#' + id + ":eq(0)").addClass('ausu-load');
                $.ajax({
                  type: config.methodType,
                    url: config.dataFile,
              dataType: "html",
                  data: "data=" + dataInput + "&id=" + id + config.addParams,
                success: function(data){
                    if(data.length >0)
                    {
                        $('#'+id).parent('div.' + config.className).children('div.ausu-suggestionsBox').fadeIn();
                        $('#'+id).parent('div.' + config.className).find('.ausu-suggestionsBox > ul').html(data);
                        $('#'+ id + ":eq(0)").removeClass('ausu-load');
                    }
                    else
                        $('#' + id + ":eq(0)").removeClass('ausu-load');
                }
              });
            }
        }

        function keyEvent (fieldChild,action)
        {
            yx = 0;
            fieldChild.find("li").each(function(){
                if($(this).attr("class") == "selected")
                yx = 1;
            });
            if(yx == 1)
            {
                var sel = fieldChild.find("li[class='selected']");
                (action=='next') ? sel.next().addClass("selected") : sel.prev().addClass("selected");
                sel.removeClass("selected");
            }
            else
                (action=='next') ? fieldChild.find("li:first").addClass("selected") : fieldChild.find("li:last").addClass("selected");
        }

        function offFocus(fieldChild)
        {
            var fieldParent =  $(fieldChild).parents('div.' + config.className);
            fieldParent.children('div.ausu-suggestionsBox').delay(config.fadeTime).fadeOut();
        }

        $(".ausu-suggestionsBox > ul li").live("click", function()
        {
            var fieldParent = $(this).parents('div.' + config.className);
            fieldParent.children('input:eq(0)').val($(this).text());
            if (config.rtnIDs==true) fieldParent.children('input:eq(1)').val($(this).attr("id"));
            fieldParent.children('div.ausu-suggestionsBox').hide();
        });

    };
})(jQuery);

[/js]

Un saludo
  • 0

#3 madri09

madri09

    Advanced Member

  • Miembros
  • PipPipPip
  • 72 posts

Posted 29 October 2012 - 03:09 PM

Compañeros ninguna idea?
  • 0

#4 madri09

madri09

    Advanced Member

  • Miembros
  • PipPipPip
  • 72 posts

Posted 30 October 2012 - 03:16 PM

Estoy probando con este autocompletar que es mas sencillo pero no consigo hacerlo funcionar.Podeis decirme por favor donde está el error?

buscar.php


<?php

if(isset($_GET['numtelefono']) && $_GET['numtelefono'] !="")
{
require_once('Connections/conexion.php');

$sql="select telefono from usuarios whrere telefono like '".$_GET['numtelefono']."%'";

mysql_query($sql,$miconexion) or die (mysql_error());

while ($fila=mysql_fetch_assoc($resultado))

echo "<li>".$fila['telefono']."</li>\n";

}

?>



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>
<script language="javascript" src="js_menu/jquery.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Documento sin título</title>
<script language="javascript">
$(document).ready(function()
{
$("#telefono").keyup(function()
{
  $.get('buscar.php' ,{ numtelefono: $("#telefono").val() }, function(datos)
  {
  if (datos!="")
 
      $("#zonaresultado").addClass("zonaconborde");
  else
  $("#zonaresultado").removeClass("zonaconborde");
 
  $("#zonaresultado").html(datos);
 
  },"txt");
});
}); // JavaScript Document
</script>
<style>
.enlace_sugerencia_over{
background-color: #3366CC;
}

div.zonaconborde{

margin-top:5px;
margin-left:165px;
width:153px;
background-color:#FFFFFF;
text-aling: left;
border: 1px solid #000000;
}

li{
list-style:none;
}

body{
background-color:#CF9;

}
#telefono{
font-size:12px;
font-style:italic;

}
</style>
</head>
<body>
<td width="9%"><input name="telefono" id="telefono" type="text" size="9" /></td>
<div id="zonaresultado"></div>
</body>
</html>


Gracias
  • 0




IP.Board spam blocked by CleanTalk.