I’m having trouble in parsing my JSON data in jQuery autocomplete. My JSON comes from this code:
<cfset theQ = lcase(q)>
<cfquery datasource="#source#" name="qry" maxrows="20">
select top 10 lastname
from info
where
lower(lastname) like '#theQ#%'
order by lastname
</cfquery>
<!---
Before we can serialize the query, we need to convert
it to an array of structs.
--->
<cfset rows = [] />
<!--- Loop over the query to convert it. --->
<cfloop query="qry">
<!--- Create a row struct. --->
<cfset row = {} />
<!--- Add each column to our struct. --->
<cfloop
index="column"
list="#qry.columnList#"
delimiters=",">
<cfset row[ column ] = qry[ column ][ qry.currentRow ] />
</cfloop>
<!--- Append the row struct to the row array. --->
<cfset arrayAppend( rows, row ) />
</cfloop>
<!---
Now that we have converted our query to an
array of structs, we can serialize it using the
serializeJSON() method.
--->
<cfset serializedQuery = serializeJSON( rows ) />
<cfoutput>#serializedQuery#</cfoutput>
I converted my query into array of structures and then serialized it to JSON. Now, parsing this JSON in jQuery autocomplete does not work. The data I get looks like this:
[{"lastname":"abc"},{"lastname":"def"},{"lastname":"ghi"}]
Here is the code for autocomplete:
$(document).ready(function() {
$("#name").autocomplete("data/name.cfm",{
minChars:1,
delay:10,
autoFill:false,
matchSubset:false,
matchContains:1,
cacheLength:10,
selectOnly:1,
dataType: 'json',
parse: function(data) {
var parsed = [];
var dataParsed = $.parseJSON(data);
for (var i = 0; i < dataParsed.length; i++) {
parsed[parsed.length] = {
data: dataParsed[i],
value: dataParsed[i].lastname,
result: dataParsed[i].lastname
};
}
return parsed;
},
formatItem: function(item) {
return item;
}
});
When I type in the text field, I get the whole JSON string as the search result. I’ve looked into other codes for parsing but still I can’t get it working. Any help? Thanks.
References:
Simon Whatley for autocomplete;
Ben Nadel for query to array of structs and serialize to json
One problem is that in your for loop you are iterating up to
data.lengthwhen you should be iterating up todataParsed.lengthIf you are using the Simon Whatley autocomplete plug-in, according to the demo on his website, the plugin simply expected the autocomplete results to be on individual lines, e.g:
So you should get rid of the
parsefunction you provide in jquery, and modify your coldfusion script to return one name per line i.e.abc\ndef\n...No need to use json or anything else. (at least thats how this demo on his website works http://www.simonwhatley.co.uk/examples/autocomplete/jquery/data/country.php)Just to confirm, you should add an
alert('aaa')to the inside of yourparse()function, I bet you will see that it is never being called.