I'm trying to use ajax on some auto generated html elements from django. I saw that you do this by selecting the instances via the class, but I can't seem to get it working. What do I have wrong here?
javascript
$(document).ready(function() {
$('.fix-button').on('submit', function(event) {
event.preventDefault();
var $issue_id = $(this);
$.ajax({
url: '{% url "fix_issue" %}',
type: 'POST',
datatype: 'json',
data: {
issueid: $issue_id.val(),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
action: 'post'
},
success: function (json) {
document.getElementById("fixed_bool").innerHTML = json['result']
console.log(json)
},
error: function (xhr, errmsg, err) {
}
});
});
});
html
<button class = "fix-button" value = "{{ issue.id }}">Fix</button>
views.py
def FixView(request):
if request.POST.get('action') == 'post':
result = ''
id = int(request.POST.get('issueid'))
issue = get_object_or_404(Issue, id=id)
if issue.fixed == False:
issue.fixed = True
result = str(issue.fixed)
issue.save()
else:
issue.fixed = False
result = str(issue.fixed)
issue.save()
return JsonResponse({'result': result, })
CodePudding user response:
You're trying to add an eventlistener to essentially, a list, instead of a single element.
Try using the .each()
method after grabbing the element.
CodePudding user response:
The backend was actually working, but the label that switches between true and false was the thing that wasn't properly updating. To fix this, I added unique id's to the label, <span id = "{{ issue.id }}">{{ issue.fixed }}</span>
and got the unique id using
var issue_id = $(this).val()
document.getElementById(issue_id).innerHTML = json['result']