Issue
I have a django project that shows a list of "issue" objects, and each issue object has a boolean field called "fixed". I want the user to be able to press a button that will change "fixed" using ajax, but the button only changes one of the issue objects rather than whatever "issue" that button belongs to, here's a gif of my problem
Here is my html:
{% for issue in projects.issues.all %}
<article class="media content-section">
<img class="rounded-circle article-img" src="{{ issue.author.profile.image.url }}">
<div class="media-body">
<div class="article-metadata">
<a class="mr-2">{{ issue.author }}</a>
<small class="text-muted">{{ issue.date_posted|date:"F d, Y" }}</small>
</div>
<h2><a class="article-title" href="{% url 'issue-detail' issue.id %}">{{ issue.title }}</a></h2>
<p class="article-content">{{ issue.description }}</p>
<p>{{ issue.severity }}</p>
{% if projects.author == user %}
<span id="fixed_bool">{{ issue.fixed }}</span>
{% csrf_token %}
<button class = "btn btn-primary btn-sm" id="fix-button" value = "{{ issue.id }}">Fix</button>
{% endif %}
</div>
</article>
{% endfor %}
Javascript:
$(document).on('click', '#fix-button', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '{% url "fix_issue" %}',
data: {
issueid: $('#fix-button').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) {
}
});
})
my url
path('fix/', views.FixView, name='fix_issue'),
and my views
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, })
Any help is greatly appreciated. Thank you!!
Solution
The id
attribute in HTML must be unique.
But every button has the same id: id="fix-button"
.
Therefore, in your JS code, this—$('#fix-button').val()
—returns always the first button's value.
To fix this, either create unique ids for each button, or use classes:
<button class="fix-button">...</button>
And in your JS code, select the buttons by class name:
$(document).on('click', '.fix-button', function (e) {
...
issueid: $(this).val(),
}
Answered By - xyres
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.