Django and Ajax : how to make a submit button? -


i new jquery , ajax , got trouble submit data ajax (which have been told do). followed these examples : how post jquery/ajax in django? , django jquery post request, did not me achieve 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 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 submit using submit button, post 200, fine, got "no ajax" print though request.post print showing correctly csrf token , 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 doing wrong ?

your request submitted form submit, not ajax request.you can use 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 csrfmiddlewaretoken in ajax request. preventdefault() called avoid default event handler


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -