Reputation: 5132
When I write print request.POST['video'], nothing gets printed in the console even through there is a value for 'video'. Am I incorrectly getting the wrong value in the javascript? I am trying to get the 'video34' (the value in the hidden field) to show up.
I am trying to POST data using jQuery/AJAX in Django and am having trouble. How do I access the 'video' variable in the views.py? When I write 'print video' in views.py, I get an error in the console saying POST /edit_favorites/ HTTP/1.1" 500 10113.
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def edit_favorites(request):
if request.is_ajax():
message = "Yes, AJAX!"
else:
message = "Not Ajax"
return HttpResponse(message)
url(r'^edit_favorites/', 'edit_favorites'),
<form method='post' id ='test'>
<input type="hidden" value="video34" />
<input type='submit' value='Test button'/>
<div id = 'message'>Initial text</div>
</form>
<script type="text/javascript">
$(document).ready(function() {
$("#test").submit(function(event){
event.preventDefault();
$.ajax({
type:"POST",
url:"/edit_favorites/",
data: {
'video': $('#test').val() // from form
},
success: function(){
$('#message').html("<h2>Contact Form Submitted!</h2>")
}
});
return false;
});
});
</script>
Upvotes: 1
Views: 1769
Reputation: 23296
In the message you got in the console POST /edit_favorites/ HTTP/1.1" 500 10113
, the "500" is the key. It means there's an error in your server code, most likely. In this case you're trying to 'print' a nonexistent variable. I'm surprised in fact that you don't see a traceback for a NameError
somewhere.
I'm not a Django user so maybe someone else can chime in with a better recommendation, but according to the Django docs all the post arguments are in request.POST
which is a dict-like object.
I'd suggest checking:
if request.method == 'POST':
if 'video' in request.POST:
video = request.POST['video']
# Do stuff, etc...
else:
# Raise an error
That's on the server side. In your HTML you also need to give names to all your form input fields. For example <input name="video" type="hidden" value="video32" />
or the like. You may wish to read up more on HTML form posting.
Upvotes: 2
Reputation: 599490
It's in request.POST['video']
, just like in a normal POST.
Upvotes: 4