Reputation: 13
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.
Upvotes: 1
Views: 1515
Reputation: 680
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);
});
});
});
Upvotes: 2