lat long
lat long

Reputation: 930

Adding django view result from ajax as table in template

I have a django model and I view i am aggregating few columns and filtering result and returning as below

def show_grid_summery(request):
    id = request.GET.get('id', None)

    context = {
        "summery": [],
    }

    result = Records.objects.filter(grid_id_id = id).aggregate(Sum('house_count'), Sum('point_count'))
    if len(result) != 0:
        context["summery"].append([result['house_count__sum'], result['point_count__sum']])


    return JsonResponse(context)

And on the template i am getting results using ajax

$.ajax({
                    url: 'ajax/summery/',

                    data: {
                      'id': ID
                    },

                    dataType: 'json',

                    success: function (data) {
                        alert(data);

                        var trHTML = '';
                        document.getElementById('summaryLabel').innerHTML = '';

                        $.each(data.summery , function (item) {
                            trHTML += '<tr><td>' + item[0] + '</td><td>' + item[1] + '</td></tr>';
                        });
                        $('#summaryLabel').append(trHTML);
                    }

Now I want to fill the results record (2 columns) as a table inside the #summaryLabel tag. (preferably with headers as well). But I am unable to sort it out after many different attempts.

html part is

<table id="summaryLabel">
            <p>information.</p>
</table>

Upvotes: 0

Views: 1271

Answers (1)

little_birdie
little_birdie

Reputation: 5857

The jQuery $.each() function passes two parameters, the first is the array index, the second is the object. So it would seem that in your code, your item variable would contain the index, which is not what you want.

Try:

$.each(data['summery'] , function (i, item) {
    trHTML += '<tr><td>' + item[0] + '</td><td>' + item[1] + '</td></tr>';
});

or just

$.each(data['summery'] , function () {
    trHTML += '<tr><td>' + this[0] + '</td><td>' + this[1] + '</td></tr>';
});

jQuery $.each() is documented here: http://api.jquery.com/jquery.each/

Upvotes: 2

Related Questions