user8390325
user8390325

Reputation:

How to dynamically generate html list from json array received via ajax call?

I am a Django novice attempting to build an app that allows users to add tracks to a playlist. I use sessions to generate a list of track id strings in a view and return an http response with the serialized array. The problem is that trying to iterate through the array in the template to build an ordered list does not format properly. It displays as a python list instead of the expected bulleted html list.

Any help would be greatly appreciated!

the Div

<!DOCTYPE html>

<div id="playlist">
<ol>
{% for track in playlist %}
    <li>{{track}}</li>
{% endfor %}
</ol>
</div>
</html>

the javascript

<script type="text/javascript">
    $(document).on('submit', '.track_form', function() {
        var $form = $(this);
            $.ajax({
                url: $form.attr('action'),
                data: $form.serialize(),
                type: $form.attr('method'),
                success: function (data) {

                    $("#playlist").html(data);
                },
                error: function(data) {
                    console.log('There was a problem');
                }
             });
             return false;    
         });
</script>

the view

def artistpage(request):
    if request.method == 'POST':
        session_playlist = request.session.get('session_playlist', [])
        tname = str(request.POST.get('track_name'))
        session_playlist.append(tname)
        request.session['session_playlist'] = session_playlist

        return HttpResponse(json.dumps(session_playlist))

Upvotes: 2

Views: 4677

Answers (1)

viveksyngh
viveksyngh

Reputation: 787

Since you are using ajax call to make request, you need to create html list in javascript code. Django template will not work in this case. Once your ajax call returns success you can create list html like this.

<script type="text/javascript">
$(document).on('submit', '.track_form', function() {
    var $form = $(this);
        $.ajax({
            url: $form.attr('action'),
            data: $form.serialize(),
            type: $form.attr('method'),
            success: function (data) {
                var list_html = "<ol>";
                for( var i=0; i <data.length; i++) {
                   list_html += "<li>" + data[i] + "</li>";
                 }
                list_html += "</ol>"
                $("#playlist").html(list_html);
            },
            error: function(data) {
                console.log('There was a problem');
            }
         });
         return false;    
     });

Your html should look like this.

<!DOCTYPE html>
  <div id="playlist">
  </div>
</html>

So your view should look something like this.

def artistpage(request):
    if request.method == 'POST':
        session_playlist = request.session.get('session_playlist', [])
        tname = str(request.POST.get('track_name'))
        session_playlist.append(tname)
        request.session['session_playlist'] = session_playlist

       return HttpResponse(json.dumps(session_playlist), content_type="application/json")

Upvotes: 4

Related Questions