babbaggeii
babbaggeii

Reputation: 7737

How to pass django ajax data to template?

I'm trying to pass a 2d array into a template via ajax. I managed to get the data from the server on click, but I don't know how I can handle that data inside a template. For instance, if I put the returned 'data' into a div then it just lists the first column. How to access specific data with, for instance:

{% for printers in printer_list %}
    {{ printer.email }}
{% endfor %}

Javascript:

$(".printersToggle").click(function() {
    $.get("/ajax", function(data) {
        /* What goes here? */
    });
});

views.py:

def ajax_test(request):
    if request.is_ajax():
        printer_list = User.objects.all()
    else:
        printer_list = "Not ajax"
    return HttpResponse(printer_list)
    # Am I doing this bit right?

urls.py:

url(r'^ajax$','website.views.ajax_test'),

Upvotes: 0

Views: 3258

Answers (2)

jondykeman
jondykeman

Reputation: 6272

Views.py

Below we are receiving an AJAX POST and filtering an object based on 'VarID', and building a list of dictionaries that each contain an OptionID, OptionValue, and OptionLabel value. Finally, you should convert whatever list or dict or combo that you want in json.

   def currentoptions(request):
        if request.is_ajax():
            currentOptions = Option.objects.filter(VariableID=int(request.POST['VarID']))
            response = []
            for i in currentOptions:
                vallabel = {}
                vallabel['OptionID'] = i.id
                vallabel['OptionValue'] = i.Value
                vallabel['OptionLabel'] = i.Label
                response.append(vallabel)
            json = simplejson.dumps(response)
            return HttpResponse(json, mimetype="text/json")
        else:
            pass

Javascript needed for CSRF reasons.

<script type="text/javascript"> 
jQuery(document).ajaxSend(function(event, xhr, settings) {
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    function sameOrigin(url) {
        // url could be relative or scheme relative or absolute
        var host = document.location.host; // host + port
        var protocol = document.location.protocol;
        var sr_origin = '//' + host;
        var origin = protocol + sr_origin;
        // Allow absolute or scheme relative URLs to same origin
        return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
            (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
            // or any other URL that isn't scheme relative or absolute i.e relative.
            !(/^(\/\/|http:|https:).*/.test(url));
    }
    function safeMethod(method) {
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
});
</script>

Javascript for your specific AJAX request.

To display the values from the dicts in the lists we are iterating through the returned data on success of the AJAX request. The JS functions are done with jQuery.

function AddOptions(VarID){
           $.ajax({
                type:"POST",
                url:"{% url builder.views.currentoptions %}",
                data: {VarID: VarID},
                success: function(data){
                $('#OptionTable > tbody > tr').remove();
                  $.each(data, function(index) {
                  $('#OptionTable > tbody:last').append('<tr id=Option_'+data[index].OptionID+'><td>'+data[index].OptionValue+'</td><td>'+data[index].OptionLabel+'</td><td><a href="#" onClick="deleteOption('+data[index].OptionID+')"><i class="icon icon-remove"></i></a>');
                  });
                }
              });
           }

Upvotes: 2

Mikael
Mikael

Reputation: 3236

This has to be done using javascript. Once the template is generated on the server and the page is displayed in the visitors web browser it is nothing more than HTML with JavaScript. In order to manipulate the page you need to use JavaScript.

Upvotes: 0

Related Questions