jquery, ajax: several post-requests instead of one -
i using django , jquery , try change button view after submit without page reloading. when press first time okay, second press lead 2 post-requests, third 3 , etc , button doesn't change anymore. although data in databases changes should every button pressing.
please, me find out wrong jquery code , how prevent post requests multiplication
function send() { $('.valid').submit(function() { var a_id = $(this).attr('a_id'); var vl = $(this).attr('vl'); $.ajax( { data: {'a_id' : a_id}, type: 'post', url: 'vl/', success: function(data, status) { $('#mark_'+a_id).html('<i class="icon-white icon-ok"></i> correct!') $('#mark_'+a_id).attr("id",'cor_'+a_id); $('#cor_'+a_id).html('not correct') $('#cor_'+a_id).attr("id",'mark_'+a_id); }, error: function(xhr, data) { alert('fail: ' + data +' answer #'+ a_id); } }); }); }
a_id answer id , comes button in template
{% if answer.validity %} <button id="cor_{{ answer.id }}" class="btn btn-inverse js-mark " a_id="{{answer.id}}" onclick = "send()" ><i class="icon-white icon-ok"></i> correct answer</button> {% else %} <button id="mark_{{ answer.id }}" class="btn btn-inverse js-mark" a_id="{{answer.id}}" onclick = "send()" >mark answer correct</button> {% endif %}
the views.py part:
def question_vl(request, question_id): context_instance=requestcontext(request) question = get_object_or_404(question, pk=question_id) if request.user == question.author: if request.method == 'post': if(request.post.get('a_id')): = answer.objects.get(pk=request.post.get('a_id')) if a.validity==false: a.validity = true else: a.validity = false a.save() return httpresponse("")
this line
$('.valid').submit(function()
attaches submit event form. whenever press button function "send" attaches same event again.
modify buttons:
{% if answer.validity %} <button class="btn btn-inverse js-mark" a_id="{{answer.id}}" onclick = "send(this)" ><i class="icon-white icon-ok"></i> correct answer</button> {% else %} <button class="btn btn-inverse js-mark" a_id="{{answer.id}}" onclick = "send(this)" >mark answer correct</button> {% endif %}
modify function way:
function send(button) { button = $(button); var a_id = button.attr('a_id'); $.ajax( { data: {'a_id' : a_id}, type: 'post', url: 'vl/', success: function(data, status) { if (data.validity){ button.html('<i class="icon-white icon-ok"></i> correct!') } else { button.html('not correct!') } }, error: function(xhr, data) { alert('fail: ' + data +' answer #'+ a_id); } }); }
your server side script should return json data actual value of "validity"
Comments
Post a Comment