html response to be loaded in a div

81 views
Skip to first unread message

João Marques

unread,
Feb 18, 2015, 1:27:26 PM2/18/15
to django...@googlegroups.com
Hey guys, so basicly I want to send a GET request with ajax to one of my views and the specific view returns an html response that will be loaded on a div.
The problem is that is doesn't seems to work at all. Nothing happers on the div.

Please help me community! Thank you!


HTML to be filled with the response:

<div id="content"></div>


GET REQUEST:


 $.ajax({
                    type: 'GET',
                    url: 'saveToDbAndReturn',
                    data: {sols: holder}
                }).done(function (response) {
                   document.getElementById("content").innerHTML = response;

                });



VIEW:

def saveToDbAndReturn(request):

    if(request.GET.get('sols', ''))=='':
        return HttpResponseRedirect("/")
    else:
        sols = json.loads(request.GET.get('sols', ''))


        for i in range(0, len(sols)):

            new_entry = Solution(fullArray=sols[i])
            new_entry.save()

    return render_to_response('saveToDbAndReturn.html', {'sols': sols})


saveToDbAndReturn.html


<div class="panel panel-default">

{% for i in range(sols) %}

    <div class="panel-heading" role="tab" id="heading{{i}}">
      <h4 class="panel-title">
        <a data-toggle="collapse" data-parent="#accordion" href="#collapse{{i}}" aria-expanded="true" aria-controls="collapse{{i}}">
            {{i}}
        </a>
      </h4>
    </div>
    <div id="collapse{{i}}" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="heading{{i}}">
      <div class="panel-body">
        {{sols[i]}}
      </div>
    </div>
{% endfor %}

</div>


Variable sol
:

Just so you get an idea, the array sols is someting like this [ [[1, 2] , [3,4]] , [[4,5,6],[2,21,9]] ]

Vijay Khemlani

unread,
Feb 18, 2015, 2:48:48 PM2/18/15
to django...@googlegroups.com
What is the actual content of the response you are getting from the AJAX request?

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/a4a2f0f7-0f6c-4918-8c01-669ff9a0f563%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

João Marques

unread,
Feb 18, 2015, 4:47:03 PM2/18/15
to django...@googlegroups.com
Im getting nothing really... I just do alert(response); and nothing shows up.

Vijay Khemlani

unread,
Feb 18, 2015, 5:05:05 PM2/18/15
to django...@googlegroups.com
When you access the AJAX resource directly from your browser (http://127.0.0.1:8000/..../saveToDbAndReturn?sols=....) are you also getting a blank page?

Also try putting a print statement or debugging poing (using pdb) at the beginning of the controller and check if it is actually being called.

Tom Evans

unread,
Feb 18, 2015, 6:07:01 PM2/18/15
to django...@googlegroups.com
On Wed, Feb 18, 2015 at 1:27 PM, João Marques <joao669...@gmail.com> wrote:
> Hey guys, so basicly I want to send a GET request with ajax to one of my
> views and the specific view returns an html response that will be loaded on
> a div.
> The problem is that is doesn't seems to work at all. Nothing happers on the
> div.
>
> Please help me community! Thank you!

How have you debugged it so far?

>
>
> HTML to be filled with the response:
>
> <div id="content"></div>
>
>
> GET REQUEST:
>
> $.ajax({
> type: 'GET',
> url: 'saveToDbAndReturn',
> data: {sols: holder}
> }).done(function (response) {
> document.getElementById("content").innerHTML = response;
>
> });

This is a GET request. It should be trivial to open the URL in a
browser, no AJAX. Does it render the correct content? If it doesn't,
fix that first.

Next, what jumps out is the URL. You've specified 'saveToDbAndReturn',
which is a relative URL. Javascript will evaluate that relative to the
current page, so if the current page is "/foo/bar/", it will attempt
to open "/foo/bar/saveToDbAndReturn'.

Is that the right URL?
What response status code do you get from the webserver for this AJAX
request? Use Web Inspector/firebug to determine.

PS: this is jquery?

$('#content').load('saveToDbAndReturn', {sols: holder})

PPS:

Views which modify data should not be GET requests. RFC2616 (HTTP) and
django's own docs:

In particular, the convention has been established that the GET and
HEAD methods SHOULD NOT have the significance of taking an action
other than retrieval. These methods ought to be considered "safe".
This allows user agents to represent other methods, such as POST, PUT
and DELETE, in a special way, so that the user is made aware of the
fact that a possibly unsafe action is being requested.

Ideally, views that modify data should not present data either. If
that behaviour is desired, on a successful data modification the view
can redirect to another url to render the newly stored information.

>
>
>
> VIEW:
>
> def saveToDbAndReturn(request):
>
> if(request.GET.get('sols', ''))=='':
> return HttpResponseRedirect("/")
> else:
> sols = json.loads(request.GET.get('sols', ''))

Arbitrarily loading user input as JSON might not be wise...

>
>
> for i in range(0, len(sols)):
>
> new_entry = Solution(fullArray=sols[i])
> new_entry.save()

Ugly and inefficient. No need to count things, no need for multiple queries:

Solution.objects.bulk_create([
Solution(fullArray=datum)
for datum in sols
])

>
> return render_to_response('saveToDbAndReturn.html', {'sols': sols})
>
>
> saveToDbAndReturn.html
>
> <div class="panel panel-default">
>
> {% for i in range(sols) %}

PPPS:

You can't do that in templates. However, within any {% for %} loop,
django is already counting. Do this instead:

{% for elem in sols %}
<div class="panel-heading" role="tab" id="heading{{ forloop.counter0 }}">

>
> <div class="panel-heading" role="tab" id="heading{{i}}">
> <h4 class="panel-title">
> <a data-toggle="collapse" data-parent="#accordion"
> href="#collapse{{i}}" aria-expanded="true" aria-controls="collapse{{i}}">
> {{i}}
> </a>
> </h4>
> </div>
> <div id="collapse{{i}}" class="panel-collapse collapse in"
> role="tabpanel" aria-labelledby="heading{{i}}">
> <div class="panel-body">
> {{sols[i]}}

PPPPS:

This is not how to access the i-th member of an array in django
templates. In fact, there is not a way to do that without using a
custom tag. However, if you rewrite your loop logic as suggested in
the PPPS, you don't need to do that, just "{{ elem }}"

Cheers

Tom

João Marques

unread,
Feb 18, 2015, 8:28:08 PM2/18/15
to django...@googlegroups.com
Thank you so much for all the answers so far. I must say that I totally failed not checking the method that both of you guys presented (just acessing the GET url on the browser).

I actually gives me an error:

ValueError(errmsg("Expecting value", s, err.value)) from None

I've searched and it seems to be my json that is not well built, altough the content is being loaded sucessfully to the database.

João Marques

unread,
Feb 18, 2015, 8:37:57 PM2/18/15
to django...@googlegroups.com
This is what is being sent to the view:

%5B%5B%5B%275E%27,%20%2710A%27,%20%278D%27%5D,%20%5B%278B%27,%20%2711B%27,%20%2712G%27%5D,%20%5B%278C%27,%20%277B%27%5D,%20%5B%2712C%27,%20%2711F%27,%20%276A%27%5D,%5B%275E%27,%20%2710G%27,%20%2710H%27%5D,%5B%278A%27,%2711E%27%5D,%20%5B%277A%27,%20%2712E%27,%20%2712F%27%5D,%20%5B%275A%27,%20%2711C%27,%20%2712B%27,%2711G%27%5D,%20%5B%277E%27,%20%2711A%27,%20%276E%27%5D,%20%5B%2710F%27,%20%2712D%27%5D,%20%5B%279E%27,%2710D%27,%20%2712A%27%5D,%20%5B%276C%27,%20%279C%27,%2710E%27%5D,%20%5B%279D%27,%20%275C%27,%20%278E%27%5D,%20%5B%277C%27,%20%2710B%27%5D,%20%5B%279B%27,%20%276B%27%5D,%20%5B%276D%27,%20%279A%27%5D,%5B%2711D%27,%275D%27%5D,%20%2710C%27,%20%275B%27%5D,%20%5B%277D%27%5D,%202800%5D,%20%5B%5B%279E%27,%20%2711G%27,%20%2712B%27,%20%2711C%27%5D,%20%5B%2710H%27,%20%279E%27,%20%2712A%27%5D,%20%5B%2710E%27,%2712C%27,%20%275D%27%5D,%20%5B%276E%27,%2011B%27,%20%277E%27,%20%2712F%27%5D,%20%5B%2712E%27,%20%2710B%27,%20%278E%27,%275C%27%5D,%20%5B%2711D%27,%20%275B%27%5D,%20%5B%277A%27,%20%279D%27,%20%2711E%27%5D,%5B%276A%27,%20%2711A%27,%20%277D%27%5D,%20%5B%279B%27,%20%275E%27,%2710A%27%5D,%20%5B%2710C%27,%20%277C%27%5D,%20%5B%278A%27,%20%2710D%27%5D,%20%5B%276C%27,%20%279A%27,%20%2712D%27%5D,%20%5B%2712G%27,%20%276D%27%5D,%5B%2710F%27%5D,%5B%279C%27,%20%2710G%27%5D,%20%5B%2711F%27,%276B%27%5D,%20%5B%278B%27%5D,%20%5B%278D%27%5D,%20%5B%277B%27,%20%278C%27%5D,%20%5B%275A%27%5D,%202700%5D%5D

instead of:

[[['5E', '10A', '8D'], ['8B', '11B', '12G'], ['8C', '7B'], ['12C', '11F', '6A'],['5E', '10G', '10H'],['8A','11E'], ['7A', '12E', '12F'], ['5A', '11C', '12B','11G'], ['7E', '11A', '6E'], ['10F', '12D'], ['9E','10D', '12A'], ['6C', '9C','10E'], ['9D', '5C', '8E'], ['7C', '10B'], ['9B', '6B'], ['6D', '9A'],['11D','5D'], '10C', '5B'], ['7D'], 2800], [['9E', '11G', '12B', '11C'], ['10H', '9E', '12A'], ['10E','12C', '5D'], ['6E', 11B', '7E', '12F'], ['12E', '10B', '8E','5C'], ['11D', '5B'], ['7A', '9D', '11E'],['6A', '11A', '7D'], ['9B', '5E','10A'], ['10C', '7C'], ['8A', '10D'], ['6C', '9A', '12D'], ['12G', '6D'],['10F'],['9C', '10G'], ['11F','6B'], ['8B'], ['8D'], ['7B', '8C'], ['5A'], 2700]]


Altough when I reach the view, the content that is loaded to the db is the right one

Thomas Rega

unread,
Feb 18, 2015, 8:44:20 PM2/18/15
to django...@googlegroups.com
Hi,

may be that this example(s) help:
https://godjango.com/blog/working-with-json-and-django/

good luck
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users...@googlegroups.com.
> To post to this group, send email to django...@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/158965f3-09d9-4bfe-a66a-1f353698bffd%40googlegroups.com.

Mario Gudelj

unread,
Feb 18, 2015, 11:59:39 PM2/18/15
to django...@googlegroups.com
You may need to use | safe filter in your tag since your output is being encoded.

E.g.

{{output|safe}}

Cheers,

M

Vijay Khemlani

unread,
Feb 19, 2015, 3:10:51 AM2/19/15
to django...@googlegroups.com
What is being sent to the view from the browser is fine, it's just being url encoded, the actual value is something like this then:

[[['5E', '10A', '8D'], ['8B', '11B', '12G'], ['8C', '7B'], ['12C', '11F', '6A'],['5E', '10G', '10H'],['8A','11E'], ['7A', '12E', '12F'], ['5A', '11C', '12B','11G'], ['7E', '11A', '6E'], ['10F', '12D'], ['9E','10D', '12A'], ['6C', '9C','10E'], ['9D', '5C', '8E'], ['7C', '10B'], ['9B', '6B'], ['6D', '9A'],['11D','5D'], '10C', '5B'], ['7D'], 2800], [['9E', '11G', '12B', '11C'], ['10H', '9E', '12A'], ['10E','12C', '5D'], ['6E', 11B', '7E', '12F'], ['12E', '10B', '8E','5C'], ['11D', '5B'], ['7A', '9D', '11E'],['6A', '11A', '7D'], ['9B', '5E','10A'], ['10C', '7C'], ['8A', '10D'], ['6C', '9A', '12D'], ['12G', '6D'],['10F'],['9C', '10G'], ['11F','6B'], ['8B'], ['8D'], ['7B', '8C'], ['5A'], 2700]]

If that's exactly the values you are sending then you have two problems:

1. You are missing a bracket at the beginning (you need 4 brackets, not 3)

2. You are missing a pair of quotes in the second apparition of / 11B" /

It should be like this

[[[["5E", "10A", "8D"], ["8B", "11B", "12G"], ["8C", "7B"], ["12C", "11F", "6A"],["5E", "10G", "10H"],["8A","11E"], ["7A", "12E", "12F"], ["5A", "11C", "12B","11G"], ["7E", "11A", "6E"], ["10F", "12D"], ["9E","10D", "12A"], ["6C", "9C","10E"], ["9D", "5C", "8E"], ["7C", "10B"], ["9B", "6B"], ["6D", "9A"],["11D","5D"], "10C", "5B"], ["7D"], 2800], [["9E", "11G", "12B", "11C"], ["10H", "9E", "12A"], ["10E","12C", "5D"], ["6E", "11B", "7E", "12F"], ["12E", "10B", "8E","5C"], ["11D", "5B"], ["7A", "9D", "11E"],["6A", "11A", "7D"], ["9B", "5E","10A"], ["10C", "7C"], ["8A", "10D"], ["6C", "9A", "12D"], ["12G", "6D"],["10F"],["9C", "10G"], ["11F","6B"], ["8B"], ["8D"], ["7B", "8C"], ["5A"], 2700]]

Or this if you are using it in the url

%5B%5B%5B%5B%225E%22%2C%20%2210A%22%2C%20%228D%22%5D%2C%20%5B%228B%22%2C%20%2211B%22%2C%20%2212G%22%5D%2C%20%5B%228C%22%2C%20%227B%22%5D%2C%20%5B%2212C%22%2C%20%2211F%22%2C%20%226A%22%5D%2C%5B%225E%22%2C%20%2210G%22%2C%20%2210H%22%5D%2C%5B%228A%22%2C%2211E%22%5D%2C%20%5B%227A%22%2C%20%2212E%22%2C%20%2212F%22%5D%2C%20%5B%225A%22%2C%20%2211C%22%2C%20%2212B%22%2C%2211G%22%5D%2C%20%5B%227E%22%2C%20%2211A%22%2C%20%226E%22%5D%2C%20%5B%2210F%22%2C%20%2212D%22%5D%2C%20%5B%229E%22%2C%2210D%22%2C%20%2212A%22%5D%2C%20%5B%226C%22%2C%20%229C%22%2C%2210E%22%5D%2C%20%5B%229D%22%2C%20%225C%22%2C%20%228E%22%5D%2C%20%5B%227C%22%2C%20%2210B%22%5D%2C%20%5B%229B%22%2C%20%226B%22%5D%2C%20%5B%226D%22%2C%20%229A%22%5D%2C%5B%2211D%22%2C%225D%22%5D%2C%20%2210C%22%2C%20%225B%22%5D%2C%20%5B%227D%22%5D%2C%202800%5D%2C%20%5B%5B%229E%22%2C%20%2211G%22%2C%20%2212B%22%2C%20%2211C%22%5D%2C%20%5B%2210H%22%2C%20%229E%22%2C%20%2212A%22%5D%2C%20%5B%2210E%22%2C%2212C%22%2C%20%225D%22%5D%2C%20%5B%226E%22%2C%20%2211B%22%2C%20%227E%22%2C%20%2212F%22%5D%2C%20%5B%2212E%22%2C%20%2210B%22%2C%20%228E%22%2C%225C%22%5D%2C%20%5B%2211D%22%2C%20%225B%22%5D%2C%20%5B%227A%22%2C%20%229D%22%2C%20%2211E%22%5D%2C%5B%226A%22%2C%20%2211A%22%2C%20%227D%22%5D%2C%20%5B%229B%22%2C%20%225E%22%2C%2210A%22%5D%2C%20%5B%2210C%22%2C%20%227C%22%5D%2C%20%5B%228A%22%2C%20%2210D%22%5D%2C%20%5B%226C%22%2C%20%229A%22%2C%20%2212D%22%5D%2C%20%5B%2212G%22%2C%20%226D%22%5D%2C%5B%2210F%22%5D%2C%5B%229C%22%2C%20%2210G%22%5D%2C%20%5B%2211F%22%2C%226B%22%5D%2C%20%5B%228B%22%5D%2C%20%5B%228D%22%5D%2C%20%5B%227B%22%2C%20%228C%22%5D%2C%20%5B%225A%22%5D%2C%202700%5D%5D

Message has been deleted

João Marques

unread,
Feb 19, 2015, 10:44:47 PM2/19/15
to django...@googlegroups.com
Thank You guys for all the aswers. Your were crucial debugging this error.

By the way, on the GET request matter, I'm using a GET because I can't actually get POST to work I'll explain: As I execute the POST request, the url is loaded and everything runs fine except that the code on the view doesn't return nothing. Thats is the reason I have everything set uo with GET. Does anybody know if I have to enable something on my Django properties to get this to work?

Cheers

Vijay Khemlani

unread,
Feb 20, 2015, 12:08:32 AM2/20/15
to django...@googlegroups.com
There's no "range" in django templates, you just use

{% for elem in sols %}

Regarding making the request using POST, are you sure you're not having a proble with CSRF?


It has a section for AJAX requests



--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.

João Marques

unread,
Feb 20, 2015, 12:05:16 PM2/20/15
to django...@googlegroups.com
According to Django documentation I can include a crsf token to prevent malicious acts, but it is not necessary right? Or am I getting this wrong? Because right now I wouldn't mind skipping the crsf token step for a little while I manage to get the rest of the essential things to work.

Vijay Khemlani

unread,
Feb 20, 2015, 1:23:44 PM2/20/15
to django...@googlegroups.com
Is is required by default.

I would recommend including the csrf token in your ajax request. If you still want to prevent the CSRF verification in your view then you can use the "csrf_exempt" decorator


James Schneider

unread,
Feb 20, 2015, 4:08:53 PM2/20/15
to django...@googlegroups.com

In most cases, including the CSRF token in AJAX requests is trivial, and processing the token is handled automatically by Django. I would recommend spending a few minutes to implement the CSRF protection in your code of you plan to ever move to production. It is easy enough and pays good dividends later.

-James

João Marques

unread,
Feb 20, 2015, 7:13:15 PM2/20/15
to django...@googlegroups.com
Oh I see. Meanwhile I'm trying to implement the token but I cant get this to work, I copied the code from Django's docs and now Im getting a javascript error syaing that the function sameOrigin is not defined.


Code

    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 csrfSafeMethod(method) {
        // these HTTP methods do not require CSRF protection
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }
    function sameOrigin(url) {
        // test that a given url is a same-origin 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));
    }
    $.ajaxSetup({
        beforeSend: function(xhr, settings) {
            if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) {
                // Send the token to same-origin, relative URLs only.
                // Send the token only if the method warrants CSRF protection
                // Using the CSRFToken value acquired earlier
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            }
        }
    });

Vijay Khemlani

unread,
Feb 21, 2015, 2:20:28 AM2/21/15
to django...@googlegroups.com
If you're using jQuery 1.5.1 or above you can do this instead

// using jQuery
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;
}

var csrftoken = getCookie('csrftoken');

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}

$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
Reply all
Reply to author
Forward
0 new messages