I try to update database using ajax query
I get row table id on click to send to view for updating data
but as my ajax is called twice (why?), second call reverse first call
<table>
<tbody>
{% for dcf in datacorrections %}
<tr>
<td data-toggle="tooltip" data-placement="top" title="">{{ dcf.ide }}</td>
<td data-toggle="tooltip" data-placement="top" title="" id="{{ dcf.ide }}">{{ dcf.deativated }}</td>
</tr>
{% endfor %}
</tbody>
</table>
$('body').on('click','td', function() {
var _id = $(this).attr('id');
$.ajax({
type: 'POST',
url: "{% url 'monitoring:deactivate_dcf' %}",
data: { "id" : _id },
dataType: 'html',
success: function (response) {
obj = JSON.parse(response);
},
});
});
@login_required
@csrf_exempt
def deactivate_dcf(request):
if request.is_ajax() and request.method == "POST":
datacorrection_id = request.POST.get("id")
if DataCorrection.objects.filter(ide = datacorrection_id).exists():
if DataCorrection.objects.get(ide = datacorrection_id).deativated == False:
DataCorrection.objects.filter(ide = datacorrection_id).update(deativated=True)
else:
DataCorrection.objects.filter(ide = datacorrection_id).update(deativated=False)
return JsonResponse({"response": "success",}, status=200)
else:
return JsonResponse({"response": "failed","exist":"datacorrection not exist"}, status=404)
return JsonResponse({"response":"not_ajax"}, status=200)
CodePudding user response:
Add class "clickable-td" to the clickable td:
<td data-toggle="tooltip" data-placement="top" title="" id="{{ dcf.ide }}">{{ dcf.deativated }}</td>
add this instead, it will trigger the event on this td and it should stop the propagation.
$('.clickable-td').click(function(e) {
e.preventDefault();
e.stopImmediatePropagation();
var _id = $(this).attr('id');
console.log(_id);
$.ajax({
method: 'POST',
url: "{% url 'monitoring:deactivate_dcf' %}",
data: { "id" : _id },
dataType: 'json',
success: function (response) {
console.log("we went throught !");
console.log(response);
},
})
});
If you go in the console inspector and find the console log of the ID then it should be fine.