Reputation: 489
I have a problem replacing div
element with ajax
. The idea is start/stop button. There's a list of card
elements on the page, each with its own button. Both buttons are stored in separate html
files.
work_order_start.html:
<div type="button" class="repairToggle" order_id="{{ order.id }}" func="start">
<svg>...</svg>
</div>
work_order_pause.html:
<div type="button" class="repairToggle" order_id="{{ order.id }}" func="stop">
<svg>...</svg>
</div>
Initially only one is rendered on the page based of if
condition:
{% if order.status == 'DN' %}
{% include 'mtn/work_order_pause.html' %}
{% else %}
{% include 'mtn/work_order_start.html' %}
{% endif %}
Here's my script:
var btns = document.querySelectorAll(".repairToggle");
for (i = 0; i < btns.length; i++) {
btns[i].addEventListener("click", manageOrderStatus);
}
function manageOrderStatus() {
var order_id = this.getAttribute("order_id");
var func = this.getAttribute("func");
if(func == 'start'){
var endpoint = "{% url 'ajax_start_order' %}";
} else {
var endpoint = "{% url 'ajax_stop_order' %}";
}
$.ajax({
url: endpoint,
type: "GET",
data: {
'order_id': order_id,
},
success: function (data) {
$(this).html(data);
}
});
}
and my views:
def start_repair(request):
...
return render(request, 'mtn/work_order_pause.html')
def end_repair(request):
...
return render(request, 'mtn/work_order_start.html')
The view executes correctly, but $(this).html(data);
doesn't replace one div
with another. What am i doing wrong?
Upvotes: 0
Views: 250
Reputation: 1254
$(this) refers to ajax context. You need to store $(this) in one variable outside of ajax call. Probably this will solve your problem. Without full code, not able to figure out. Check if this works
Upvotes: 1