user3033194
user3033194

Reputation: 1831

Use AJAX to display dictionary data returned by Django view in a table on the template

I saw some posts on this topic but none quite similar. I am getting back a dictionary in JSON format from a Django view as shown below:

# display game statistics on the developer homepage
def gamestats(request):

    countlist = []
    datedict = {}
    if request.method=='POST' and request.is_ajax:
        id = request.POST.get('id',None)
        gameobj = Games.objects.filter(pk=id)
        # get queryset of Scores objects with the selected game ID
        scores = Scores.objects.filter(game=gameobj)
        # get list of distinct registration dates from "scores" queryset
        datelist = scores.values_list('registration_date',flat=True).distinct()
        for dateobj in datelist:
            scoredate = scores.filter(registration_date=dateobj)
            c = scoredate.count()
            countlist.append(c)

        n = len(countlist)
        for i in range(n):
            t = datelist[i].strftime('%d/%m/%Y')
            datedict[t] = countlist[i]
            print(t)
            print(datedict[t])

        json_stats = json.dumps(datedict)
        return HttpResponse(json_stats,content_type='application/json')

This dictionary holds data in the form:

{ "29/01/2015" : 2, "21/12/2014" : 1, "23/01/2015": 3 }

Now, on the client side, the AJAX code is given below:

$(".stats").click(function(){
    var game = $(this);
    var id = game.attr('id');
    var csrftoken = getCookie('csrftoken');
    $.ajax({
        type : "POST",
        url : "/gamestats/",
        data : {'id': id, 'csrfmiddlewaretoken': csrftoken},
        dataType : "json",
        success : function(data){
            alert(data);
            //var obj = $.parseJSON(response);
            //for (var key in obj){
            //    alert("inside for loop");
            //    var value = obj[key];
            //    alert(value);
            //    $("#gamestats").html(value);
            //}
        }
    });
    event.preventDefault(); 
});

The relevant HTML code: ...

<tr>
    <td width="10%" align="center"><button class="stats" id="{{game.id}}"> View game statistics</button></td>
</tr>

...

<b>Game statistics: </b>
<p id="gamestats"></p>

Due to my very limited knowledge of AJAX, I do not know how to handle the response inside the "success" parameter of the request. I want to display the JSON data in a table, with 2 columns, one for the dates (keys) and other for the corresponding numbers (values). I want to do this inside the "gamestats" section of the page. I tried some things but they don't display anything. Any help is appreciated, thank you!!

Upvotes: 0

Views: 3577

Answers (1)

alacy
alacy

Reputation: 5074

If you want to take a JSON object and put it into a table you can loop over it like so:

var tableData = '<table>'
$.each(data, function(key, value){
        tableData += '<tr>';
        tableData += '<td>' + key + '</td>';
        tableData += '<td>' + value + '</td>';
        tableData += '</tr>';
});
tableData += '</table>';

$('#table').html(tableData);

Upvotes: 2

Related Questions