f1nn f1nn - 6 months ago 118
jQuery Question

Get POST data in django form AJAX from

I'm going to get parameter form AJAX request in Django, Here's what I'm doing:

base.html:

<form method="POST">{% csrf_token %}
First name: <input type="text">
<input type="submit" value="Register" id="register">
</form>


main.js:

$(document).ready(function(){
$("#register").live("click", function(e){
$.post("/", {
name: "MY TEXT",
});
});
});


views.py:

from django.shortcuts import render_to_response
from django.template import RequestContext
from django.core.context_processors import csrf

def home(request):
if request.method == 'POST':
print request.POST['name']
return render_to_response('registration.html', {},
context_instance=RequestContext(request))


Yes, I know that at this moment my JS doesnt get real data from text form, it sends just a static text "MY TEXT". but when I press button, I get
"MultiValueDictKeyError at /
"Key 'name' not found in ""


What I'm doing wrong?

I've changed my code:
main.js

$(document).ready(function(){
$("#register").live("click", function(e){
e.preventDefault();
$.post("/", {
name:'MY TEXT'
});
});
});


base.html:

<form method="POST">{% csrf_token %}
First name: <input type="text" name="name">
<br>
<input type="submit" value="Register" id="register">
</form>


It works, thanks!

Although, I have two questions:


  1. Where am I sending 'MY TEXT' in this case? I ment it returns the ACTUAL data from name field and doesn't return "MY TEXT"

  2. The page is still reloading. And I wanted to make it completely AJAX. I mean create a python function to add data from POST request to MySQL database, and return to AJAX-script the result of the operation. And everything without page reload. How can I do this?


Answer

What's happening is that you haven't prevented the browser's default submit action from taking place. So your Ajax POST is done, but then immediately the browser itself POSTs - and, as Michal points out, your form doesn't include a name field, so the lookup fails.

You need to do two things to fix this. Firstly, use e.preventDefault(); in your JS click method. Secondly, check for request.is_ajax() at the top of your view.