Jump to content
srf

AJAX with sorting or filtering

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.

Share this post


Link to post
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.

Share this post


Link to post
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?

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...