I am new to jQuery. Basically I have a table which I can sort the rows. I want to save the new order in the backend, which I am able to do. However, I noticed that I am sending multiple Ajax calls depending on the number of times I sorted the table. The order is not saving properly in the backend. Here is my code. The variable order is where the new IDs are stored. I am sending it in my Django through the '/updateorder' route/
<script type="text/javascript">
$(document).ready(function(){
$("#sortable").sortable({
update: function (event, ui) {
var order = $(this).sortable('toArray');
console.log(order);
$(document).on("click", "button", function () {
$.ajax({
data: {csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value, 'order[]': order},
type: 'POST',
url: '/updateorder'
})
});
}
}).disableSelection();
$('button').on('click', function () {
var r = $("#sortable").sortable("toArray");
var a = $("#sortable").sortable("serialize", {
attribute: "id"
);
console.log(r);
});
});
</script>
How can I avoid sending multiple Ajax calls when I click on the button? Also, what is the correct way to redirect to a different page after the logic is executed? Thanks for reading!
PS: I am using python/django in the backend