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.
"Reach getLists"message appear? Can you see anything in your Javascript and/or Django consoles?{% url 'getlist' %}is working properly?