JQuery: Sorting JSON results

JQuery. Write less, do more

This is a follow up to a previous post on sorting elements using JQuery. A few people messaged me asking how to modify the code to sort JSON results from a ajax request so here it goes.

The JSON (json.php):

We’re going to sort these results by the ‘name’ field and apply them to a ul list. First save the above JSON to your server and call it json.php.


That’s it! After you save the above html to your server, you should see a case-insensitive sorted list of names from your JSON file in your list. If you want to sort using another attribute besides name just modify the sortJsonName() function.

, ,

  • Katy

         function sortJsonLength(a,b){          return a.LENGTH > b.LENGTH ? 1 : -1;      };        function sortJsonTopic(a,b){          return a.TOPIC.toUpperCase() > b.TOPIC.toUpperCase() ? 1 : -1;      };    $(document).ready(function() {
    var tableHeading =  

             $.getJSON(“json.php”, function(cats){   $(‘.sort_length’).click(function() {
                            cats = $(cats).sort(sortJsonLength); 
                $(‘.sort_topic’).click(function() {
                            cats = $(cats).sort(sortJsonTopic); 
                 var lhtml = ”;              $.each(cats, function(index, cat){                        lhtml +=                         ‘                                                  ‘ + value[‘QUESTION_DATE’] + ‘ ‘ + cat[‘QUESTION_TIME’] + ‘                         ‘+ cat[‘TOPIC’]+’                        ‘+ cat[‘LENGTH’] +’                    ‘;  ‘;              });              $(‘#weekly_table’).append(lhtml);          });      });        
    I can’t seem to make this work and maybe you can help me. I have two sorts going on. It should be sorted depending on what I click on the TH in the table. 

    Only problem is I can’t get the click to work, can anyone help?  If I take the on clicks out and just test to see if each sort works accordingly in the table when website loads, it does work, but I want user to click and sort it themselves.

Powered by WordPress. Designed by Woo Themes