So I’ve been following this tutorial http://webcloud.se/log/AJAX-in-Django-with-jQuery/, and the get method works fine. i.e. I get a popup saying what it should say in the popup. However when I use the post method instead I don’t get anything. It appears that the request doesn’t even reach my view.
This is what my bit of javascript dealing with this looks like:
$(document).ready(function(){
$("#popupbutton").click(function(){
$.post("/launch_instances", {
name: "Monty",
food: "Spam"
},
function(data) {
alert(data);
}
);
});
...................
This are the related bit of my template:
<center>
<div id="popupbutton"><input type="submit" value="Launch Instances!" /></div>
</center>
And here is my views.py:
from django.http import HttpResponse
def li_view(request):
return HttpResponse("post gets to the view")
if request.is_ajax():
if request.method == 'GET':
message = "This is an XHR GET request"
elif request.method == 'POST':
message = "This is an XHR POST request"
else:
message = "Nothing"
else:
message = "No XHR"
return HttpResponse(message)
As you can see the first thing I do when I get to my view is return a HttpResponse, but when I am using post I don’t see any popup like I do when I am using get. So my guess is that for some reason the request doesn’t even reach the view.
This is what my urls.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^launch_instances/', 'simdata.views.li_view'),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
)
There have been similar questions around but nothing as bizzare as this. I’m new to django/ajax/jquery so probably missing something very small.
Thanks in advance 🙂
Oh! Wow. That is such a small bug, it took me a while of staring at your code to spot it. You’re requesting
/launch_instances(notice without the trailing slash at the end). When Django encounters this, it automatically redirects the request to/launch_instances/(with trailing slash), but through the redirection, the POST data is dropped. Add the trailing slash, and you should be golden.