Dynamic filtering with jQuery and XML
Back in November I wrote a short piece on dynamic search filtering using jQuery and using ajax.load() to populate a search div. A reader asked if it was possible to do the same thing with an XML document and it is quite easy to do. I do not have it searching over multiple nodes, but with a little array-fu I imagine it can be modified to handle it.
The search page is exactly the same as the previous post, we have just modified the query.cfm to use an XML document instead. Here is our new query.cfm file:
<cfparam name="url.search" type="string" default=""> <cfsavecontent variable="books"> <?xml version="1.0"?> <books> <book> <isbn>0321330110</isbn> <title>Macromedia ColdFusion MX 7 Certified Developer Study Guide</title> <author>Ben Forta</author> </book> <book> <isbn>0596004206</isbn> <title>Learning XML, Second Edition</title> <author>Erik Ray</author> </book> <book> <isbn>0782140297</isbn> <title>Coldfusion MX Developer's Handbook</title> <author>Raymond Camden</author> </book> </books> </cfsavecontent> Search page <cfset booksXml = XmlParse(books)/> <cfset SearchByTitle = xmlSearch(booksXml,'//book [contains(title,"#url.search#")]')> <cfoutput> #arrayLen(SearchByTitle)# Book(s) Found<br /><br /> <cfloop from="1" to="#arraylen(SearchByTitle)#" index="i"> <cfset BookXML = xmlparse(SearchByTitle[i])> <b>ISBN:</b> #BookXML.book.isbn.xmltext# - <b>Title:</b> #BookXML.book.title.xmlText# - <b>Author:</b> #BookXML.book.author.xmlText# <br /> </cfloop> </cfoutput>
I have used the hard-coded XML Scott used in his tutorial, but it could easily be modified to dynamically load the XML. We are searching the Title nodes for each title that contains our search string and it is case-sensitive. I might play around with this a little more later today and see if I can make it more robust.
I have a demo of this code here: http://www.kisdigital.com/tests/filter
I did some research and found this post by Ben Nadel explaining the XmlSearch() function in detail. Expanding the search field to other nodes in the XML document is very easy. For instance, if you wanted to search on titles and authors you could modify the XmlSearch string as follows:
‘//book [(contains(title,”#url.search#”)) or (contains(author,”#url.search#”)) ]’
I think Ben’s site covers just about everything. 😉