Reputation: 94
I am using django and jQuery and I try to change button view after submit without page reloading. When I press it first time everything is okay, but the second press lead to two POST-requests, the third to three and etc and the button doesn't change anymore. Although data in databases changes as it should with every button pressing.
Please, help me to find out what is wrong with my jquery code and 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 is for answer id and it comes from 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 this answer as 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')):
a = Answer.objects.get(pk=request.POST.get('a_id'))
if a.validity==False:
a.validity = True
else:
a.validity = False
a.save()
return HttpResponse("")
Upvotes: 0
Views: 185
Reputation: 4984
This line
$('.valid').submit(function()
attaches the submit event to the form. So whenever you press the button function "send" attaches the same event again.
Modify your 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 this answer as correct</button>
{% endif %}
Modify your function this 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 with the actual value of "validity"
Upvotes: 1