Reputation: 11
I am trying to make a post request with jquery in Django. Unfortunately I haven't succeeded yet. Indeed : I only see in firebug a post request which status is 200 and I get the following result (too new to post any image):
https://drive.google.com/a/essec.edu/file/d/0B5MagNFQFkbXeVBNV1pfZC1sbk0/view?usp=sharing
Could anyone help me find what I have done wrong?
My code comes from here : Need a simple working ajax example for django forms , so I think it should be correct.
FYI, in settings.py I have commented the csrf line to put away that issue for the time beeing :
" #'django.middleware.csrf.CsrfViewMiddleware',"
views.py:
import json
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return render(request, 'index.html')
def ajax_test(request):
if request.method == 'POST' and request.is_ajax():
name = request.POST['name']
city = request.POST['city']
message = name + ' lives in ' + city
return HttpResponse(json.dumps({'message': message}))
return render(request, 'ajax.html')
index.html:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="/static/js/ajax.js"></script>
<script src="http://getbootstrap.com/dist/js/bootstrap.js"></script>
<form id="my_form" action="" method="post">
<input type="submit" value="Send">
</form>
ajax.js:
$(document).ready(function(){
$("#my_form").submit(function(){
$.post("",
{name:"Donald Duck",
city:"Duckburg",
},
function(data,status){
alert("Data: " + data + "\nStatus: " + status);
})
.fail(function(xhr) {
console.log("Error: " + xhr.statusText);
alert("Error: " + xhr.statusText);
});
return false;
});
});
urls.py:
from django.conf.urls import patterns, url
from polls import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^ajax/$', views.ajax_test, name="ajax"),
)
Upvotes: 1
Views: 1061
Reputation: 235
Your form has no "action" defined
$.post("",
This must have the url defined. Change it to
$.post("/ajax/",
Also when you implement it properly, don't get rid of the csrf token. You can simply pass the serialized form data (which will include the csrf token).
Upvotes: 0
Reputation: 2089
I would bet for your form action. Try setting it to the URL of your post.
Upvotes: 1