Need a simple working ajax example for django forms

Basically I need something similar to http://www.w3schools.com/jquery/jquery_ajax_get_post.asp in django. I downloaded the samples and tested them locally with localhost + php and it works fine, but I can't get it to work in django no matter how simple the example is. Here is basically what I did based on the above example with a little modification

javascript:

<script type="text/javascript"> $(document).ready(function(){ $("#my_form").submit(function(){ $.post("", {name:"Donald Duck", city:"Duckburg"}, function(data,status){ alert("Data: " + data + "\nStatus: " + status); }) .fail(function() { alert("error"); }); return false; }); }); </script> 

URL:

 url(r'^ajax/$', views.ajax_test, name="ajax"), 

kinds:

 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})) #tried without the json. Doesn't work either return render(request, 'books/ajaxTest.html') 

html:

 <form id="my_form" action="" method="post" {% if form.is_multipart %}enctype="multipart/form-data"{% endif %}>{% csrf_token %} <input type="submit" value="Send"> </form> 

The form should include the django form, but since I can't even get the basics to work, it would be pointless. Someone mentioned the csrf_token tag, but deleting does not solve the problem either. The result of the above example basically just gives a warning ("error") and nothing else. I went through many examples, but I can’t even get the most basic ones for work.

+7
source share
1 answer

OK..thanks for your comments .. I sorted it all out. I just skipped {% csrf_token%} and csrfmiddlewaretoken: '{{csrf_token}}' .. just for the benefit of those who might be reading this ... the new codes will look something like this.

javascript:

 <script type="text/javascript"> $(document).ready(function(){ $("#my_form").submit(function(){ $.post("", {name:"Donald Duck", city:"Duckburg", csrfmiddlewaretoken:'{{ csrf_token }}' }, function(data,status){ alert("Data: " + data + "\nStatus: " + status); }) .fail(function(xhr) { console.log("Error: " + xhr.statusText); alert("Error: " + xhr.statusText); }); return false; }); }); </script> 

html:

 <form id="my_form" action="" method="post">{% csrf_token %} <input type="submit" value="Send"> </form> 
+8
source

All Articles