Search code examples
ajaxautocompletecoldfusion-8

autocomplete in coldfusion 8


I need to add the autocomplete widget to search for a word from the database,even if the characters are in the middle of the word This My CFM page :

      <script src="jquery-1.4.2.min.js"></script>
      <script src="jquery-ui-1.8.custom.min.js"></script>
      <link rel="stylesheet" href="jquery-ui-1.8.custom.css" type="text/css" />

      <script type="text/javascript">
        $(document).ready(function(){ 
        $('#Names').autocomplete( 
                   {source: function(request, response) { 
                     $.ajax({ 
                     url: "cfc/getValues.cfc?method=getNames>&returnformat=json", 
                     dataType: "json", 
                     data: { 
                     search: request.term, 
                     maxRows: 10 
                     }, 
                  success: function(data) { 
                  response(data); 
                    }                    
                  }) 
              }, 
            parse: function(data){ 
                  return $.map(data, function(item) { 
                  return { data: item, value: item, result: item }; 
                }); 
               } 
             }); 
           }); 
      </script>

     category: <input id="Names" />

and this the CFC page:

    //cfc file getValues.cfc

   <cffunction name="getNames" access="remote" returntype="String" > 
     <cfargument name="search" type="any" required="false" default="">   
      <cfset var data=""> 
        <cfset var result=ArrayNew(1)> 
           <cfquery name="data" datasource="dbNAme"> 
            SELECT  NAME 
            FROM myTable 
            WHERE NAME LIKE '%#trim(ARGUMENTS.search)#%' 
            ORDER BY NAME 
           </cfquery> 
        <cfloop query="data"> 
        <cfset returnStruct = StructNew() /> 
        <cfset returnStruct["label"] = NAME />  
        <cfset ArrayAppend(result,returnStruct) /> 
        </cfloop>
       <cfreturn serializeJSON(result) /> 
       </cffunction>

No javascript error but i can't get it to work at all.when i write in the textbox nothing happens is there something wrong in my code?


Solution

  • Try this:

    <cfloop query="data">
        <cfset statesStruct = StructNew() />
        <cfset statesStruct["id"] = id />
        <cfset statesStruct["label"] = name />
        <cfset statesStruct["value"] = name />
    
        <cfset ArrayAppend(returnArray,statesStruct) />
    </cfloop>
    
    <cfoutput>
        #serializeJSON(returnArray)#
    </cfoutput>