Implementing an ajax form with Django
The problem I'm having is that, when I submit the form, the response is placed in a new url(/feedback) instead of placing it in the actual(/results) url. The alert never gets executed. I guess I'm doing something wrong in the template but I can't find the solution.
I debugged the view and made a request.is_ajax()
, it returned False.
views.py:
def ajax_feedback(request):
success = False
if request.method == "POST":
post = request.POST.copy()
if post.has_key('rel') and post.has_key('relp'):
rel = post['rel']
relp = post['relp']
q = post['query']
开发者_StackOverflow fq = post['full_query']
fq = fq[:350]
ip = request.META['REMOTE_ADDR']
feedback = FeedBack(q=q, ip_address=ip,
user=request.user, relevance=rel, rel_pages=relp,
full_query=fq)
feedback.save()
success = True
if success == True:
return HttpResponse("Success")
else:
return HttpResponse("Error")
results.html:
<form method="post" action="/feedback/" id="feedback_form">
<input type="radio" name="rel" value="yes" id="rel" /> Yes<br />
<input type="radio" name="rel" value="no" id="rel" /> No
<input type="radio" name="relp" value="1-5" id="relp" /> 1-5 <br />
<input type="radio" name="relp" value="6-10" id="relp" /> 6-10
<input type="hidden" name="query" value="{{ query }}">
<input type="hidden" name="full_query" value="{{ bq }}">
<input id="create" type="submit" value="Send">
</form>
<script>
var create_note = function() {
var rel = $("#rel").val()
var relp = $("#relp").val()
var query = {{ query }}
var full_query = {{ bq }}
var data = { rel:rel, relp:relp, query:query, full_query:full_query };
var args = {
type: "POST",
url: "/feedback/",
data: data,
success: function(msg){
alert(msg);
}
}
$.ajax(args);
return false;
};
$("#create").click(create_note);
</script>
urls.py:
...
(r'^feedback/$', views.ajax_feedback),
(r'^results/(?P<query>.+)/$', views.results),
...
You have a missing close brace after your success
function declaration. Because of this, the return false
is never reached, and your browser submits the form via normal HTTP request - which is why it's not an Ajax call when it reaches your view.
Edit well another JS bug is that you haven't put {{ query }}
and {{ bp }}
in quotes. They might or might not be valid JS objects, and if not the function will fail and never reach the return false
.
精彩评论