Skip to content

Commit

Permalink
Replace $.ajax() with fetch()
Browse files Browse the repository at this point in the history
  • Loading branch information
asdil12 and Martchus committed Sep 18, 2024
1 parent 0967772 commit e5301be
Show file tree
Hide file tree
Showing 6 changed files with 116 additions and 108 deletions.
108 changes: 55 additions & 53 deletions assets/javascripts/comments.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,6 @@ function renderCommentHeading(comment, commentId) {
return heading;
}

function showXhrError(context, jqXHR, textStatus, errorThrown) {
window.alert(context + getXhrError(jqXHR, textStatus, errorThrown));
}

function updateNumerOfComments() {
const commentsLink = document.querySelector('a[href="#comments"]');
if (commentsLink) {
Expand All @@ -51,15 +47,15 @@ function deleteComment(deleteButton) {
if (!window.confirm('Do you really want to delete the comment written by ' + author + '?')) {
return;
}
$.ajax({
url: deleteButton.dataset.deleteUrl,
method: 'DELETE',
success: () => {
fetchWithCSRF(deleteButton.dataset.deleteUrl, {method: 'DELETE'})
.then(response => {
if (response.status != 200) throw `Server returned ${response.status}: ${response.statusText}`;
$(deleteButton).parents('.comment-row, .pinned-comment-row').remove();
updateNumerOfComments();
},
error: showXhrError.bind(undefined, "The comment couldn't be deleted: ")
});
})
.catch(error => {
window.alert(`The comment couldn't be deleted: ${error}`);
});
}

function updateComment(form) {
Expand All @@ -75,31 +71,30 @@ function updateComment(form) {
displayElements([textElement, form.applyChanges, form.discardChanges], 'none');
markdownElement.style.display = '';
markdownElement.innerHTML = '<em>Loading…</em>';
$.ajax({
url: url,
method: 'PUT',
data: $(form).serialize(),
success: () => {
$.ajax({
url: url,
method: 'GET',
success: response => {
fetchWithCSRF(url, {method: 'PUT', body: new FormData(form)})
.then(response => {
if (response.status != 200) throw `Server returned ${response.status}: ${response.statusText}`;
// get rendered markdown
fetch(url)
.then(response => {
if (response.status != 200) throw `Server returned ${response.status}: ${response.statusText}`;
return response.json();
})
.then(comment => {
const commentId = headingElement.querySelector('.comment-anchor').href.split('#comment-')[1];
headingElement.replaceWith(renderCommentHeading(response, commentId));
textElement.value = response.text;
markdownElement.innerHTML = response.renderedMarkdown;
headingElement.replaceWith(renderCommentHeading(comment, commentId));
textElement.value = comment.text;
markdownElement.innerHTML = comment.renderedMarkdown;
hideCommentEditor(form);
},
error: () => location.reload()
});
},
error: (jqXHR, textStatus, errorThrown) => {
textElement.value = text;
markdownElement.innerHTML = markdown;
showCommentEditor(form);
window.alert("The comment couldn't be updated: " + getXhrError(jqXHR, textStatus, errorThrown));
}
});
})
.catch(error => {
console.error(error);
location.reload();
});
})
.catch(error => {
window.alert(`The comment couldn't be updated : ${error}`);
});
}

function addComment(form, insertAtBottom) {
Expand All @@ -109,22 +104,26 @@ function addComment(form, insertAtBottom) {
return window.alert("The comment text mustn't be empty.");
}
const url = form.action;
$.ajax({
url: url,
method: 'POST',
data: $(form).serialize(),
success: response => {
const commentId = response.id;
fetch(url, {method: 'POST', body: new FormData(form)})
.then(response => {
if (response.status != 200) throw `Server returned ${response.status}: ${response.statusText}`;
return response.json();
})
.then(data => {
const commentId = data.id;
console.log(`Created comment #${commentId}`);
// get rendered markdown
$.ajax({
url: url + '/' + commentId,
method: 'GET',
success: response => {
fetch(`${url}/${commentId}`)
.then(response => {
if (response.status != 200) throw `Server returned ${response.status}: ${response.statusText}`;
return response.json();
})
.then(comment => {
const templateElement = document.getElementById('comment-row-template');
const commentRow = $(templateElement.innerHTML.replace(/@comment_id@/g, commentId))[0];
commentRow.querySelector('[name="text"]').value = response.text;
commentRow.querySelector('h4').replaceWith(renderCommentHeading(response, commentId));
commentRow.querySelector('.markdown').innerHTML = response.renderedMarkdown;
commentRow.querySelector('[name="text"]').value = comment.text;
commentRow.querySelector('h4').replaceWith(renderCommentHeading(comment, commentId));
commentRow.querySelector('.markdown').innerHTML = comment.renderedMarkdown;
let nextElement;
if (!insertAtBottom) {
nextElement = document.querySelectorAll('.comment-row')[0];
Expand All @@ -136,12 +135,15 @@ function addComment(form, insertAtBottom) {
$('html, body').animate({scrollTop: commentRow.offsetTop}, 1000);
textElement.value = '';
updateNumerOfComments();
},
error: () => location.reload()
});
},
error: showXhrError.bind(undefined, "The comment couldn't be added: ")
});
})
.catch(error => {
console.error(error);
location.reload();
});
})
.catch(error => {
window.alert(`The comment couldn't be added: ${error}`);
});
}

function insertTemplate(button) {
Expand Down
27 changes: 12 additions & 15 deletions assets/javascripts/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,28 +93,25 @@ function loadBuildResults(queryParams) {
};

// query build results via AJAX using parameters from filter form
$.ajax({
url: buildResultsElement.data('build-results-url'),
data: queryParams ? queryParams : window.location.search.substr(1),
success: function (response) {
showBuildResults(response);
var url = new URL(buildResultsElement.data('build-results-url'), window.location.href);
url.search = queryParams ? queryParams : window.location.search.substr(1);
fetch(url)
.then(response => {
if (response.status != 200) throw `Server returned ${response.status}: ${response.statusText}`;
return response.text();
})
.then(responsetext => {
showBuildResults(responsetext);
window.buildResultStatus = 'success';
},
error: function (xhr, textStatus, thrownError) {
// ignore error if just navigating away
if (textStatus !== 'timeout' && !xhr.getAllResponseHeaders()) {
return;
}
const error = xhr.responseJSON?.error;
})
.catch(error => {
const message = error ? htmlEscape(error) : 'Unable to fetch build results.';
showBuildResults(
'<div class="alert alert-danger" role="alert">' +
message +
'<a href="javascript:loadBuildResults();" style="float: right;">Try again</a></div>'
);
window.buildResultStatus = 'error: ' + thrownError;
}
});
});
}

function autoRefreshRestart() {
Expand Down
32 changes: 21 additions & 11 deletions assets/javascripts/openqa.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,16 @@ function setupForAll() {
});
}

function getCSRFToken() {
return document.querySelector('meta[name="csrf-token"]').content;
}

function fetchWithCSRF(resource, options) {
options.headers ??= {};
options.headers['X-CSRF-TOKEN'] ??= getCSRFToken();
return fetch(resource, options);
}

function makeFlashElement(text) {
return typeof text === 'string' ? '<span>' + text + '</span>' : text;
}
Expand Down Expand Up @@ -238,11 +248,12 @@ function restartJob(ajaxUrl, jobId) {
addFlash('danger', errorMessage);
};

return $.ajax({
type: 'POST',
url: ajaxUrl,
success: function (data, res, xhr) {
var responseJSON = xhr.responseJSON;
return fetchWithCSRF(ajaxUrl, {method: 'POST'})
.then(response => {
if (response.status != 200) throw `Server returned ${response.status}: ${response.statusText}`;
return response.json();
})
.then(responseJSON => {
var newJobUrl;
try {
newJobUrl = responseJSON.test_url[0][jobId];
Expand All @@ -261,13 +272,12 @@ function restartJob(ajaxUrl, jobId) {
if (newJobUrl) {
window.location.replace(newJobUrl);
} else {
showError('URL for new job not available');
throw 'URL for new job not available';
}
},
error: function (xhr, ajaxOptions, thrownError) {
showError(xhr.responseJSON ? xhr.responseJSON.error : undefined);
}
});
})
.catch(error => {
showError(error);
});
}

function htmlEscape(str) {
Expand Down
17 changes: 7 additions & 10 deletions assets/javascripts/overview.js
Original file line number Diff line number Diff line change
Expand Up @@ -301,20 +301,17 @@ function addComments(form) {
controls.style.display = 'inline';
window.addCommentsModal.hide();
};
$.ajax({
url: form.action,
method: 'POST',
data: $(form).serialize(),
success: response => {
fetchWithCSRF(form.action, {method: 'POST', body: new FormData(form)})
.then(response => {
if (response.status != 200) throw `Server returned ${response.status}: ${response.statusText}`;
addFlash(
'info',
'The comments have been created. <a href="javascript: location.reload()">Reload</a> the page to show changes.'
);
done();
},
error: (jqXHR, textStatus, errorThrown) => {
addFlash('danger', 'The comments could not be added: ' + getXhrError(jqXHR, textStatus, errorThrown));
})
.catch(error => {
addFlash('danger', `The comments could not be added: ${error}`);
done();
}
});
});
}
23 changes: 13 additions & 10 deletions assets/javascripts/test_result.js
Original file line number Diff line number Diff line change
Expand Up @@ -497,27 +497,30 @@ function loadTabPanelElement(tabName, tabConfig) {
return false;
}
tabConfig.panelElement = tabPanelElement; // for easier access in custom renderers
$.ajax({
url: ajaxUrl,
method: 'GET',
success: function (response) {
fetch(ajaxUrl, {method: 'GET'})
.then(response => {
if (response.status != 200) throw `Server returned ${response.status}: ${response.statusText}`;
if (response.headers.get('Content-Type').includes('application/json')) return response.json();
return response.text();
})
.then(response => {
const customRenderer = tabConfig.renderContents;
if (customRenderer) {
return customRenderer.call(tabConfig, response);
}
tabPanelElement.innerHTML = response;
},
error: function (xhr, ajaxOptions, thrownError) {
})
.catch(error => {
console.error(error);
const customRenderer = tabConfig.renderError;
if (customRenderer) {
return customRenderer.call(tabConfig, xhr, ajaxOptions, thrownError);
return customRenderer.call(tabConfig, error);
}
tabPanelElement.innerHTML = '';
tabPanelElement.appendChild(
document.createTextNode('Unable to load ' + (tabConfig.descriptiveName || tabName) + '.')
document.createTextNode('Unable to load ' + (tabConfig.descriptiveName || tabName) + `: ${error}`)
);
}
});
});
tabPanelElement.innerHTML =
'<p style="text-align: center;"><i class="fa fa-spinner fa-spin fa-lg"></i> Loading ' +
(tabConfig.descriptiveName || tabName) +
Expand Down
17 changes: 8 additions & 9 deletions assets/javascripts/tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -191,16 +191,15 @@ function changeJobPrio(jobId, delta, linkElement) {
}

var newPrio = currentPrio + delta;
$.ajax({
url: urlWithBase('/api/v1/jobs/' + jobId + '/prio?prio=' + newPrio),
method: 'POST',
success: function (result) {

fetchWithCSRF(urlWithBase(`/api/v1/jobs/${jobId}/prio?prio=${newPrio}`), {method: 'POST'})
.then(response => {
if (response.status != 200) throw `Server returned ${response.status}: ${response.statusText}`;
prioValueElement.text(newPrio);
},
error: function (xhr, ajaxOptions, thrownError) {
addFlash('danger', 'Unable to set the priority value of job ' + jobId + '.');
}
});
})
.catch(error => {
addFlash('danger', `Unable to set the priority value of job ${jobId}: ${error}`);
});
}

function renderTestSummary(data) {
Expand Down

0 comments on commit e5301be

Please sign in to comment.