Jump to content

AJAX with sorting or filtering


srf

Recommended Posts

I'm looking for a way to display the contents of an XML file on a web page with AJAX. I rely on the w3schools "simple CD catalog application", which shows a part of the XML (author and title) and, when you click on a title, displays the details of the CD. 

I need, however, to be able to add sorting and filtering when displaying artist and title - it could, for instance, be sorting the titles alphabetically or apply a filter based on the year of release. XSLT doesn't seem to work with AJAX so I hope JavaScript could be the answer: Is it possible to add such functions to the application example using JavaScript - and how could it be done? I'd really be glad if someone could help.

Link to comment
Share on other sites

AJAX is Javascript, so you have no choice but to use Javascript if you want to use AJAX.

You can sort the nodes, but it's not trivial. Do you want to change the order in the DOM itself or just what is being displayed to the user?

The sort() method of Javascript arrays can make your job easier: https://www.w3schools.com/jsref/jsref_sort.asp You will need to make a custom sorting function to deal with DOM nodes.

Link to comment
Share on other sites

Thanks for useful advice. I've looked into sort() and has actually (and finally) managed to get my script running by adding these lines where the values of the tag "id" are parsed in an array and sorted:
 

function sorting(a,b){

return parseInt(a.getElementsByTagName("id")[0].firstChild.nodeValue) - parseInt(b.getElementsByTagName("id")[0].firstChild.nodeValue);

        }   

sItems = Array.prototype.slice.call(itm);

sItems = sItems.sort(sorting);

I’d like to offer the possibility of sorting alphabetically, by “title” as well, but I simply can’t find out what the code should be changed into. Could somebody help, please?

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...