0

I am very new to jquery and Ajax and I got trouble to submit data with ajax (which is what I have been told to do). I followed these examples : How do I POST with jQuery/Ajax in Django? and Django jQuery post request, but they did not really help me to achieve my goal.

urls.py

 url(r'^rechargement/$', views.rechargement, name='rechargement'),

views.py

@login_required
def rechargement(request):
if request.POST:
    if request.is_ajax():
        print "AJAX"
    else:
        print "No AJAX"

    print request.POST
return render(request,"clients/packs.html",locals())

template

<div class="container">
  <div class="row">
    <form id="recharge" action="" method="post">
      <fieldset>
        <legend> Choose your pack</legend>
        {% csrf_token %}
        <div class="col-md-3">
          <p>Pack 1</p>
          <input type="radio" name="pack" value="pack1">
        </div>
        <div class="col-md-3">
          <p>Pack 2</p>
          <input type="radio" name="pack" value="pack2">
        </div>
        <div class="col-md-3">
          <p>Pack 3</p>
          <input type="radio" name="pack" value="pack3">
        </div>
        <div class="col-md-3">
          <p>Pack 4</p>
          <input type="radio" name="pack" value="pack4">
        </div>
        <input type="submit" value="Recharge">
      </fieldset>
    </form>
   </div>
  </div>

jquery

<script type="text/javascript">
$document.ready(function(){
  $("#recharge").submit(function(event){
$.ajax({
  type:"POST",
  url:"{% url 'rechargement' %}",
  data : {
    'pack': $('#rechargement').val()
  },
});
return false;
   };)
 });
</script>

When I submit using the submit button, I get a POST 200, which is fine, but I got the "No AJAX" print even though the request.POST print is showing correctly the csrf token and the value:

 No AJAX
 <QueryDict: {u'csrfmiddlewaretoken': [u'i************v'], u'pack': [u'pack1']}>
 [30/Sep/2015 08:57:18] "POST /clients/rechargement/ HTTP/1.1" 200 4017

What am I doing wrong ?

Community
  • 1
  • 1
Dr Mouse
  • 331
  • 1
  • 5
  • 19

1 Answers1

2

Your request is submitted as form submit, not an ajax request.You can use the following code.

$(document).ready(function(){
$('#recharge').submit(function (event) {
event.preventDefault();
$.ajax({
  type:"POST",
  url:"{% url 'rechargement' %}",
  data : {
          'pack': $('#rechargement').val(),
          'csrfmiddlewaretoken':$("input[name=csrfmiddlewaretoken]").val()
         },
   });
   return false;
   };)
});

Don't forget the csrfmiddlewaretoken in the ajax request. preventDefault() is called to avoid the default event handler

Arun K
  • 242
  • 1
  • 5