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.

Also I will note I did get most of the code from learncf.com, and more specifically http://tutorial18.learncf.com by Scott Bennett.  I just wanted to make sure I gave credit where credit was due.

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"?>
 <title>Macromedia ColdFusion MX 7 Certified Developer Study Guide</title>
 <author>Ben Forta</author>
 <title>Learning XML, Second Edition</title>
 <author>Erik Ray</author>
 <title>Coldfusion MX Developer's Handbook</title>
 <author>Raymond Camden</author>

Search page
<cfset booksXml = XmlParse(books)/>

<cfset SearchByTitle = xmlSearch(booksXml,'//book [contains(title,"#url.search#")]')>
 #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 />

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.  😉


4 thoughts on “Dynamic filtering with jQuery and XML

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s