skip to Main Content

Consider 2 files:

File 1 – list.html

<ul>
  <li>Dog</li>
  <li>Ant</li>
  <li>Cat</li>
</ul>

File 2 – ajax.html

    <html>
     <body>
      <button type="button">Click</button>
      <ul id="list">
      </ul>
      <script type="text/javascript">
        $("button").click(function() {
          $("#list").load("list.html ul > li");
        });
      </script>
     </body>
    </html>

Here file 1 contain list of items and file 2 load file 1’s li tag list items to file 2’s ul tag. After ajax call, how can we sort the loaded list alphabetically before it is displayed on the screen. I wanted to sort only after ajax call. Please help me.

2

Answers


  1. You can do this inside the ajax success callback function. Also, you can user JS .sort() for sorting the names. This is a simple ajax call. You can add more properties based on your need. let’s assume the result variable contains the names which you want to add:

    $('#myButton').click(function(){
      $.ajax({
          url : 'Your_server_url',
          success: function(result){
            result.sort()
            for (i = 0; i < result.length; i++) {
                $('#list').append("<li>" + result[i] + "</li>")
            }
          },
          error: function (xhr, status) {
              console.info("cannot update list!");
          }
       });
    
    
    });
     <html>
       <body>
          <button type="button" id="myButton">Click</button>
          <ul id="list">
          </ul>
      </body>
    </html>
    Login or Signup to reply.
  2. To do this you can provide a function to the callback argument of load() which is executed after the AJAX request completes and the new content has been added to the DOM. Try this:

    $("button").click(function() {
      let $list = $("#list").load("list.html ul > li", function() {
        $list.find('li').sort((a, b) => a.innerText < b.innerText ? -1 : 1).appendTo($list);
      });
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search