I have a function where onclick a button will get all the id of selected task from a gantt chart and run a for loop to save each of the selected task i edited in a form using AJAX request.
The problem now on AJAX request success I add a code to clear and load all the data again in the gantt chart but it doesn't goes as intended, load the data several times and start creating duplicate of the same data in my gantt, I tried to execute the gantt.load function outside of the loop and it still not working.
So how can I create a condition where I reload the gantt AFTER the loop is finish executed? Any help is much appreciated thanks.
Below is my code :
HTML
<button type="button" class="btn btn-primary" onclick="editForm()">Edit</button>
javascript
function editForm() {
var selected_task = gantt.getSelectedTasks();
for (var i = 0; i < selected_task.length; i++) {
var task = selected_task[i];
var data = gantt.getTask(task);
$.ajax({
type: 'PUT',
url: '/api/dashboard/workorder_detail/' + data.workorder_id + '/',
data: postData,
success: function () {
$('#edit_form_modal').modal('hide');
gantt.clearAll();
gantt.load("/api/scheduler/{{ selected_project.id }}/?format=json", "json");
},
error: function (err) {
alert("Failed because of " + err);
}
})
}
}
AJAXcalls are asynchronous, due to this you cannot expect synchronous codeforto wait for an asynchronous code to finish because you do not have the result at the moment the code is executed and therefore you have to wait for the result, i suggest to implement this usingPromisesas it can allow you to wait for all the asynchronous code and execute function when there's a result