0

I tried to display data using ajax, and it went perfectly. but I have problems how to create a looping based on years of my data?

year |    name    | 
___________________
2011 | John       | 
2012 | Smith      | 
2012 | Billy      | 
2011 | Charles    | 
2013 | Kitty      | 
2010 | Micheal    | 
2011 | jason      | 

Ajax data

<a href="#" onclick="show_year();"> Get </a>


function show_year() {  
    $.ajax({
        url : "<?php echo site_url('my_function/get_year')?>" ,
        type: "GET",
        dataType: "JSON",
        success: function(data)
        {
            $('#year').val(data.year);
            $('#name').val(data.name);
        },
        error: function (jqXHR, errorThrown)
        {
            alert('Error ajax');
        }       
    });         
}

Example result

2011
    John
    Charles
    Jason
2012
    Smith
    Billy
2013
    Kitty
irwan dwiyanto
  • 690
  • 1
  • 9
  • 28
  • It's not really a duplicate, since in this question the author wants to simply group simple data. As opposed to "related" question which is full of inappropriately heavy-duty examples of complicated grouping and summing. Question's title is not everything, moderators. – Wiktor Bednarz Jan 19 '17 at 09:25

1 Answers1

0
<a href="#" onclick="show_year();"> Get </a>
<div id="responseHtml"></div>
<script type="text/javascript">
    function show_year() {  
        $.ajax({
            url : "<?php echo site_url('my_function/get_year')?>" ,
            type: "GET",
            dataType: "JSON",
            success: function(data)
            {
                var sortArr = data.sort(function(x, y){
                    return x.year - y.year;
                });
                var cstYear = '';
                var ResultHtml = '';
                sortArr.foreach(function(row,index){
                    if(cstYear !== row.year){
                        cstYear == row.year;
                        ResultHtml = '<h4>'+row.year+'</h4>';
                    }
                    ResultHtml = '<h6 style="margin-left:30px">'+row.name+'</h4>';
                });
                $("#responseHtml").html(ResultHtml);
            },
            error: function (jqXHR, errorThrown)
            {
                alert('Error ajax');
            }       
        });         
    }
</script>
Harshil Patel
  • 298
  • 2
  • 8