I am trying to understand how Django + Jquery and Ajax calls work together.
It is just a simple /test/ url that shows a single input form, once submitted retrieves the answer from the server via ajax.
For that I have written a very small view:
def test(request):
if request.is_ajax():
from django.http import HttpResponse
post_text = request.POST.get("post_data")
return HttpResponse("{'response_text': '"+post_text+" recieved.'}", mimetype="application/json")
else:
return render_to_response('test.html', {},context_instance =RequestContext(request))
And I have written this url rule to my urlpattern at the urls.py:
(r'^test/$', 'myapp.views.test'),
And here is my test.html template:
<html>
<head><title>template</title></head>
<script type="text/javascript" src="/media/js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#post_form').submit(function(event){
event.preventDefault(); // cancel the default action
var form = this;
var data = {}
data.post_data = $(form).find('input[@name=our_text]').val();
$.post("/test/",
data,
function(responseData) {
alert(responseData.response_text);
},
"json"
);
});
});
</script>
<body>
<form id="post_form" method="post">
INPUT: <input type="text" name="our_text" />
<input type="submit" value="Add" />
</form>
</body>
</html>
It doesn't seem to do any reply on my www.mysite.com/test/ once I fill the input field and submit. What can be the problem?