Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace $.ajax() with fetch() #5925

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 27 additions & 22 deletions assets/javascripts/admin_assets.js
Original file line number Diff line number Diff line change
Expand Up @@ -121,37 +121,42 @@ function reloadAssetsTable() {
}

function deleteAsset(assetId) {
$.ajax({
url: urlWithBase('/api/v1/assets/' + assetId),
method: 'DELETE',
dataType: 'json',
success: function () {
fetchWithCSRF(urlWithBase(`/api/v1/assets/${assetId}`), {method: 'DELETE'})
.then(response => {
// not checking for status code as 404 case also returns proper json
return response.json();
})
.then(response => {
if (response.error) throw response.error;
addFlash(
'info',
'The asset was deleted successfully. The asset table\'s contents are cached. Hence the removal is not immediately visible. To update the view use the "Trigger asset cleanup" button. Note that this is an expensive operation which might take a while.'
"The asset was deleted successfully. The asset table's contents are cached." +
'Hence the removal is not immediately visible. To update the view use the "Trigger asset cleanup" button.' +
'Note that this is an expensive operation which might take a while.'
);
},
error: function (xhr, ajaxOptions, thrownError) {
var error_message = xhr.responseJSON.error;
addFlash('danger', error_message);
}
});
})
.catch(error => {
console.error(error);
addFlash('danger', `Error deleting asset: ${error}`);
});
}

function triggerAssetCleanup(form) {
$.ajax({
url: form.action,
method: form.method,
success: function () {
fetchWithCSRF(form.action, {method: form.method})
.then(response => {
if (!response.ok) throw `Server returned ${response.status}: ${response.statusText}`;
return response.json();
})
.then(response => {
addFlash(
'info',
'Asset cleanup has been triggered. Open the <a href="/minion/jobs?task=limit_assets">Minion dashboard</a> to keep track of the task.'
`Asset cleanup has been triggered. Open the <a href="/minion/jobs?task=limit_assets">Minion dashboard</a> to keep track of the task (gru_id #${response.gru_id}).`
);
},
error: function (xhr, ajaxOptions, thrownError) {
addFlash('danger', 'Unable to trigger the asset cleanup: ' + thrownError);
}
});
})
.catch(error => {
console.error(error);
addFlash('danger', `Unable to trigger the asset cleanup: ${error}`);
});
}

function showLastAssetStatusUpdate(assetStatus) {
Expand Down
98 changes: 56 additions & 42 deletions assets/javascripts/admin_groups.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,21 +37,23 @@ function showError(message) {
}

function fetchHtmlEntry(url, targetElement) {
$.ajax({
url: url,
method: 'GET',
success: function (response) {
fetch(url)
.then(response => {
if (!response.ok) throw `Server returned ${response.status}: ${response.statusText}`;
return response.text();
})
.then(response => {
var element = $(response);
element.hide();
targetElement.prepend(element);
$('#new_group_creating').hide();
$('#add_group_modal').modal('hide');
element.fadeIn('slow');
},
error: function (xhr, ajaxOptions, thrownError) {
showError(thrownError + ' (requesting entry HTML, group probably added though! - reload page to find out)');
}
});
})
.catch(error => {
console.error(error);
showError(`${error} (requesting entry HTML, group probably added though! - reload page to find out)`);
});
}

function countEmptyInputs(form) {
Expand Down Expand Up @@ -87,7 +89,7 @@ function createGroup(form) {
$('#new_group_error').hide();
$('#new_group_creating').show();

let data = $(form).serialize();
let data = new FormData(form);
let postUrl, rowUrl, targetElement;
if (form.dataset.createParent !== 'false') {
postUrl = form.dataset.postParentGroupUrl;
Expand All @@ -99,36 +101,26 @@ function createGroup(form) {
const parentId = form.dataset.parentId;
if (parentId !== 'none') {
targetElement = $('#parent_group_' + parentId).find('ul');
data += '&parent_id=' + parentId;
data.set('parent_id', parentId);
} else {
targetElement = $('#job_group_list');
}
}

$.ajax({
url: postUrl,
method: 'POST',
data: data,
success: function (response) {
if (!response) {
showError('Server returned no response');
return;
}
var id = response.id;
if (!id) {
showError('Server returned no ID');
return;
}
fetchWithCSRF(postUrl, {method: 'POST', body: data})
.then(response => {
if (!response.ok) throw `Server returned ${response.status}: ${response.statusText}`;
return response.json();
})
.then(response => {
if (!response) throw 'Server returned no response';
if (!response.id) throw 'Server returned no ID';
fetchHtmlEntry(rowUrl + response.id, targetElement);
},
error: function (xhr, ajaxOptions, thrownError) {
if (xhr.responseJSON.error) {
showError(xhr.responseJSON.error);
} else {
showError(thrownError);
}
}
});
})
.catch(error => {
console.error(error);
showError(error);
});

return false;
}
Expand Down Expand Up @@ -262,24 +254,25 @@ function saveReorganizedGroups() {
var updateJobGroupUrl = jobGroupList.data('put-job-group-url');

// event handlers for AJAX queries
var handleError = function (xhr, ajaxOptions, thrownError) {
var handleError = function (error) {
console.error(error);
$('#reorganize_groups_panel').show();
$('#reorganize_groups_error').show();
$('#reorganize_groups_progress').hide();
$('#reorganize_groups_error_message').text(thrownError ? thrownError : 'something went wrong');
$('#reorganize_groups_error_message').text(error ? error : 'something went wrong');
$('html, body').animate({scrollTop: 0}, 1000);
};

var handleSuccess = function (response, groupLi, index, parentId) {
if (!response) {
handleError(undefined, undefined, 'Server returned nothing');
handleError('Server returned nothing');
return;
}

if (!response.nothingToDo) {
var id = response.id;
if (!id) {
handleError(undefined, undefined, 'Server returned no ID');
handleError('Server returned no ID');
return;
}

Expand All @@ -292,7 +285,7 @@ function saveReorganizedGroups() {

if (ajaxQueries.length) {
// do next query
$.ajax(ajaxQueries.shift());
handleQuery(ajaxQueries.shift());
} else {
// all queries done
if (showPanelTimeout) {
Expand Down Expand Up @@ -325,7 +318,7 @@ function saveReorganizedGroups() {
ajaxQueries.push({
url: updateGroupUrl + groupId,
method: 'PUT',
data: {
body: {
sort_order: groupIndex,
parent_id: 'none',
drag: 1
Expand All @@ -350,7 +343,7 @@ function saveReorganizedGroups() {
ajaxQueries.push({
url: updateJobGroupUrl + jobGroupId,
method: 'PUT',
data: {
body: {
sort_order: childGroupIndex,
parent_id: groupId,
drag: 1
Expand All @@ -366,9 +359,30 @@ function saveReorganizedGroups() {
});

if (ajaxQueries.length) {
$.ajax(ajaxQueries.shift());
handleQuery(ajaxQueries.shift());
} else {
handleSuccess({nothingToDo: true});
}
return false;
}

function handleQuery(query) {
const url = query.url;
delete query.url;
const success = query.success;
delete query.success;
const error = query.error;
delete query.error;
var body = new FormData();
for (const key in query.body) {
body.append(key, query.body[key]);
}
query.body = body;
fetchWithCSRF(url, query)
.then(response => {
if (!response.ok) throw `Server returned ${response.status}: ${response.statusText}`;
return response.json();
})
.then(success)
.catch(error);
}
20 changes: 11 additions & 9 deletions assets/javascripts/admin_needle.js
Original file line number Diff line number Diff line change
Expand Up @@ -158,10 +158,12 @@ function setupAdminNeedles() {
deleteBunchOfNeedles();
};

$.ajax({
url: url + nextIDs.join('&id='),
type: 'DELETE',
success: function (response) {
fetchWithCSRF(url + nextIDs.join('&id='), {method: 'DELETE'})
.then(response => {
if (!response.ok) throw `Server returned ${response.status}: ${response.statusText}`;
return response.json();
})
.then(response => {
// add error affecting all deletions
var singleError = response.error;
if (singleError) {
Expand Down Expand Up @@ -191,11 +193,11 @@ function setupAdminNeedles() {
});

deleteBunchOfNeedles();
},
error: function (xhr, ajaxOptions, thrownError) {
handleSingleError(thrownError);
}
});
})
.catch(error => {
console.error(error);
handleSingleError(error);
});

return true;
};
Expand Down
51 changes: 24 additions & 27 deletions assets/javascripts/admin_user.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,46 +22,43 @@ function setup_admin_user() {
return;
}

var data = form.serializeArray();
var newRole = data[1].value;
var data = new FormData(form[0]);
var newRole = data.get('role');

$.ajax({
type: 'POST',
url: form.attr('action'),
data: jQuery.param(data),
success: function (data) {
fetch(form.attr('action'), {method: 'POST', body: data})
.then(response => {
if (!response.ok) throw `Server returned ${response.status}: ${response.statusText}`;
findDefault(form).removeClass('default');
form.find('input[value="' + newRole + '"]').addClass('default');
},
error: function (err) {
})
.catch(error => {
console.error(error);
rollback(form);
addFlash('danger', 'An error occurred when changing the user role');
}
});
addFlash('danger', `An error occurred when changing the user role: ${error}`);
});
});

window.deleteUser = function (id) {
if (!confirm('Are you sure you want to delete this user?')) return;

$.ajax({
url: urlWithBase('/api/v1/user/' + id),
method: 'DELETE',
dataType: 'json',
success: function () {
fetchWithCSRF(urlWithBase('/api/v1/user/' + id), {method: 'DELETE'})
.then(response => {
if (response.status == 500)
throw 'An internal server error has occurred. Maybe there are unsatisfied foreign key restrictions in the DB for this user.';
if (!response.ok) throw `Server returned ${response.status}: ${response.statusText}`;
return response.json();
})
.then(response => {
if (response.error) throw response.error;
addFlash('info', 'The user was deleted successfully.');
window.admin_user_table
.row($('#user_' + id))
.remove()
.draw();
},
error: function (xhr, ajaxOptions, thrownError) {
if (xhr.responseJSON && xhr.responseJSON.error) addFlash('danger', xhr.responseJSON.error);
else
addFlash(
'danger',
'An error has occurred. Maybe there are unsatisfied foreign key restrictions in the DB for this user.'
);
}
});
})
.catch(error => {
console.error(error);
addFlash('danger', error);
});
};
}
23 changes: 11 additions & 12 deletions assets/javascripts/admin_worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,18 +61,17 @@ function loadWorkerTable() {

function deleteWorker(deleteBtn) {
var post_url = $(deleteBtn).attr('post_delete_url');
$.ajax({
url: post_url,
method: 'DELETE',
dataType: 'json',
success: function (data) {
fetchWithCSRF(post_url, {method: 'DELETE'})
.then(response => {
return response.json();
})
.then(response => {
if (response.error) throw response.error;
var table = $('#workers').DataTable();
table.row($(deleteBtn).parents('tr')).remove().draw();
addFlash('info', data.message);
},
error: function (xhr, ajaxOptions, thrownError) {
var message = xhr.responseJSON.error;
addFlash('danger', "The worker couldn't be deleted: " + message);
}
});
addFlash('info', response.message);
})
.catch(error => {
addFlash('danger', "The worker couldn't be deleted: " + error);
});
}
Loading
Loading