Jump to content

Recommended Posts

I am retrieving data using AJAX. I would like to sort them from newest to oldest date. Currently they show from oldest to newest.

How do I do that?

<div id="output"></div>
<script>
  $(document).ready(function(){
    $.ajax ({
      type: 'GET',
      url: "https://3rdpartywebsite.com/api/getcustomers",
      dataType: 'json',
      success: function(data) {
       $.each(data, function(i, v) {

         var customerId 		   = v.customerId;
         var firstName 			   = v.firstName;
         var lastName  			   = v.lastName;
         var createdDateTime 	   = v.createdDateTime;

          $('#output').append('<ul class="output-ul">' + '<li>' + customerId + '</li>' + '<li>' + firstName + '</li>' + '<li>' + lastName + '</li>' +   '<li>' + createdDateTime + '</li>' + '</ul>');
       });
      }
    });
  });
</script>

 

Link to comment
https://forums.phpfreaks.com/topic/311712-how-do-i-sort-the-results-by-date/
Share on other sites

3 minutes ago, requinix said:

 

I was hoping for a simpler solutions where someone can edit my code to include the sort by. I've been researching and trying to do it myself but no luck so far.

 

Also I am noticing that the page load time increases every time I submit the record and  I retrieve them from the API. It really shouldn't be taking a min to load 20 records from the API. 

Do you think if I create a pagination that it'll slow the load time? Or you think it's an issue on the API party's end?

5 hours ago, imgrooot said:

Or you think it's an issue on the API party's end?

That kinda depends on the third-party's API. If you make the call in Postman does it take a minute? Honestly, the fact that the load time increases each time you submit the page makes me think it's the PHP, but I haven't looked that closely at your code.

8 hours ago, imgrooot said:

Does the "3rd Party Website API" offer a method by which you can retrieve the data in the order you want? 
That would be easiest. 

Failing that, you're just going to have to take the data as it is provided and then do the sorting yourself. 
If you're really lucky, the dates will already be in a sortable format ... 

Regards, 
   Phill  W.

Here's an example script

<?php
require 'db_inc.php';
$db = pdoConnect('test');

/* MY DATA ********************************************************************************************************
                TABLE: a_student
                +------------+----------+---------------------+
                | student_id | fullname | logged              |
                +------------+----------+---------------------+
                |          1 | Peter    | 2020-08-02 17:23:56 |
                |          2 | Paul     | 2020-08-22 23:23:56 |
                |          3 | Mary     | 2020-07-28 22:23:56 |
                |          4 | Cath     | 2020-01-25 04:23:56 |
                |          5 | Dave     | 2020-01-04 18:23:56 |
                |          6 | Eric     | 2020-02-12 07:23:56 |
                |          7 | Fred     | 2020-10-23 06:23:56 |
                |          8 | John     | 2020-07-19 11:23:56 |
                |          9 | Jane     | 2020-07-28 15:23:56 |
                |         10 | Alec     | 2020-05-06 02:23:56 |
                |         11 | Ben      | 2020-04-07 15:23:56 |
                +------------+----------+---------------------+
*******************************************************************************************************************/

//
//  Process AJAX request
//
if (isset($_GET['ajax']) && $_GET['ajax']=='getstudents') {
    $res = $db->query("SELECT student_id
                            , fullname
                            , logged
                       FROM a_student;    
                      ");
    exit(json_encode($res->fetchAll()));
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="creation-date" content="11/16/2020">
<title>Primes</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<script type='text/javascript'>
    $().ready( function() {
        $("button").click( function() {
            var dir = $(this).data("dir");
            getStudents(dir)
        })
    })
    
    function getStudents(dir)
    {
        if (dir == 'asc') {
            sortfunc = function(a,b) {
                if ( a.logged < b.logged ) return -1
                else if (a.logged > b.logged ) return 1
                else return 0
            }
        }
        else {
            sortfunc = function(a,b) {
                if ( b.logged < a.logged ) return -1
                else if (b.logged > a.logged ) return 1
                else return 0
            }
        }
        $.get (
            "",
            {"ajax":"getstudents"},
            function(resp) {
                resp.sort(sortfunc)
                $("#student-list").html("")
                $(resp).each( function (k, v) {
                    $("#student-list").append("<tr><td>"+v.student_id+"</td><td>"+v.fullname+"</td><td>"+v.logged+"</td></tr>")
                })
            },
            "JSON"
        )
    }
</script>
<style type='text/css'>
    table {
        width: 500px;
        font-family: verdana, sans-serif;
        font-size: 11pt;
    }
    th {
        background-color: black;
        color: white;
        padding: 8px;
    }
    td {
        padding: 4px 8px;
    }
</style>
</head>
<body>
<button data-dir='asc'>Oldest to Newest</button> &emsp; <button data-dir='desc'>Newest to Oldest</button>
<hr>
<table>
    <tr><th>ID</th><th>Name</th><th>Date</th></tr>
    <tbody id='student-list'>
    
    </tbody>
</table>
</body>
</html>

image.png.e66a921a583f592e471b46f0b9aefa42.png

 

 

 

Edited by Barand
add sample output
14 hours ago, imgrooot said:

I would like to sort them from newest to oldest date. Currently they show from oldest to newest.

If you're sure they are returned in oldest to newest (rather than that being just by chance) then you could simply reverse the array.

If you need more control, then see the other replies for details on implementing a sort.

 

On 11/16/2020 at 4:36 PM, kicken said:

If you're sure they are returned in oldest to newest (rather than that being just by chance) then you could simply reverse the array.

If you need more control, then see the other replies for details on implementing a sort.

 

Wow that was a simple solution. It works now.

Here is the update code. All I had to do was add ".reverse()" to the each data.

<div id="output"></div>
<script>
  $(document).ready(function(){
    $.ajax ({
      type: 'GET',
      url: "https://3rdpartywebsite.com/api/getcustomers",
      dataType: 'json',
      success: function(data) {
       $.each(data.reverse(), function(i, v) {

         var customerId 		   = v.customerId;
         var firstName 			   = v.firstName;
         var lastName  			   = v.lastName;
         var createdDateTime 	   = v.createdDateTime;

          $('#output').append('<ul class="output-ul">' + '<li>' + customerId + '</li>' + '<li>' + firstName + '</li>' + '<li>' + lastName + '</li>' +   '<li>' + createdDateTime + '</li>' + '</ul>');
       });
      }
    });
  });
</script>

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

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.   Restore formatting

  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.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.