1

Ajax code cannot send request to server, but when I make regular http request to the same url, it can work. I have tried to substitute the url field to the "http://" url, still cannot work. Anybody has idea?

Environment:

django 1.5.4;
python 2.7.4;
jquery 2.0.3;

test.html

<html>
    <head>
            <title></title>
            <script type='text/javascript' src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
            <script type="text/javascript">
            $(document).ready(function() {
                    $("#button").click(function(){
                            $.ajax({
                                    type : "POST",
                                    url : "{% url 'getlist' %}",
                                    data : {
                                            msg : 'abcd'
                                    },
                            }).done(function(data){
                                    alert(data.message);
                            });
                    });
            });     
            </script>
    </head>
    <body>
            <input id="button" type="button" value="Get message from server!">
            {% if resource_list %}
            <ul>
                    {% for resource in resource_list %}
                    <li><a href="{{ resource.url }}">{{ resource.name }}</a></li>
                    {% endfor %}
            </ul>
            {% else %}
            <p>No Resources</p>
            {% endif %}
    </body>

view.py

def getList(request):
    print "Reach getLists"
    if request.is_ajax():
            try:
                    msg = request.POST['msg']
            except:
                    return HttpResponse(simplejson.dumps({'message':'Error From Server'}))
            return HttpResponse(simplejson.dumps({'message':msg}))
    else:
            return HttpResponse(simplejson.dumps({'message':'Not an ajax request'}))

urls.py

url(r'^test$', views.test),
url(r'^getlist/$', views.getList, name='getlist'),

==================================== Update ===================================== Error Info

Forbidden (403)

CSRF verification failed. Request aborted. Help Reason given for failure: CSRF token missing or incorrect.

============================== Resolved ==================================
Solution: After add "csrfmiddlewaretoken:'{{ csrf_token }}', " in data field of JavaScript file, it worked. The reason is django has enabled CSRF protection.

============================== Thanks ====================================
Thanks to the help of @dkp2442 and @Christian Ternus, especially @dkp2442.

6
  • 1
    What errors are you getting? Does the "Reach getLists" message appear? Can you see anything in your Javascript and/or Django consoles? Commented Oct 8, 2013 at 18:57
  • 1
    Have you viewed source on the rendered template to make sure the {% url 'getlist' %} is working properly? Commented Oct 8, 2013 at 19:04
  • @Christian Ternus The "Reach getLists" message cannot show when click the button, but it shows when accessed by browser's http request. Previously, I added an alert to show the error information, and the information is 403: undefined. Commented Oct 8, 2013 at 19:38
  • @dpk2442 After render, the {% url 'getlist' %} in ajax code has been substituted by /getlist/. Commented Oct 8, 2013 at 19:39
  • If you are using a browser like Chrome, when you look at the javascript console, is anything printed when you click the button? Commented Oct 8, 2013 at 19:52

2 Answers 2

2

Well I created a gist but made it secret somehow (can I edit that?? lol). Anyway, you need to include the csrftoken in your post. Here is my answer:

    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;
    }

You can use that getCookie function for any of your posts, just include it like so:

     $(document).ready(function() {
        $("#button").click(function(){
            $.ajax({
                type : "POST",
                url : "{% url 'getlist' %}",
                data : {
                    msg : 'abcd',
                    csrfmiddlewaretoken: getCookie('csrftoken')
                }
            }).done(function(data){
                alert(data.message);
            });
        });
    });
Sign up to request clarification or add additional context in comments.

Comments

0

Read the ajax section on the django docs page on csrf.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.