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 17, 2024
1 parent 0967772 commit 94de1d1
Show file tree
Hide file tree
Showing 4 changed files with 79 additions and 77 deletions.
102 changes: 49 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}`);

Check failure on line 52 in assets/javascripts/comments.js

View workflow job for this annotation

GitHub Actions / Lint JavaScript code (using Node version 20)

Replace `(`Server·returned·${response.status}:·${response.statusText}`)` with `·`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}`);

Check failure on line 57 in assets/javascripts/comments.js

View workflow job for this annotation

GitHub Actions / Lint JavaScript code (using Node version 20)

Delete `··`
});
}

function updateComment(form) {
Expand All @@ -75,31 +71,27 @@ 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}`);

Check failure on line 76 in assets/javascripts/comments.js

View workflow job for this annotation

GitHub Actions / Lint JavaScript code (using Node version 20)

Replace `(`Server·returned·${response.status}:·${response.statusText}`)` with `·`Server·returned·${response.status}:·${response.statusText}``
// get rendered markdown
fetch(url)
.then(response => {
if (response.status != 200) throw(`Server returned ${response.status}: ${response.statusText}`);

Check failure on line 80 in assets/javascripts/comments.js

View workflow job for this annotation

GitHub Actions / Lint JavaScript code (using Node version 20)

Replace `(`Server·returned·${response.status}:·${response.statusText}`)` with `·`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()});

Check failure on line 90 in assets/javascripts/comments.js

View workflow job for this annotation

GitHub Actions / Lint JavaScript code (using Node version 20)

Replace `console.error(error);·location.reload()` with `⏎··········console.error(error);⏎··········location.reload();⏎········`
})
.catch(error => {
window.alert(`The comment couldn't be updated : ${error}`);

Check failure on line 93 in assets/javascripts/comments.js

View workflow job for this annotation

GitHub Actions / Lint JavaScript code (using Node version 20)

Delete `··`
});
}

function addComment(form, insertAtBottom) {
Expand All @@ -109,22 +101,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}`);

Check failure on line 106 in assets/javascripts/comments.js

View workflow job for this annotation

GitHub Actions / Lint JavaScript code (using Node version 20)

Replace `(`Server·returned·${response.status}:·${response.statusText}`)` with `·`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}`);

Check failure on line 115 in assets/javascripts/comments.js

View workflow job for this annotation

GitHub Actions / Lint JavaScript code (using Node version 20)

Replace `(`Server·returned·${response.status}:·${response.statusText}`)` with `·`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 +132,12 @@ 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()});

Check failure on line 136 in assets/javascripts/comments.js

View workflow job for this annotation

GitHub Actions / Lint JavaScript code (using Node version 20)

Replace `console.error(error);·location.reload()` with `⏎··········console.error(error);⏎··········location.reload();⏎········`
})
.catch(error => {
window.alert(`The comment couldn't be added: ${error}`);

Check failure on line 139 in assets/javascripts/comments.js

View workflow job for this annotation

GitHub Actions / Lint JavaScript code (using Node version 20)

Delete `··`
});
}

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
10 changes: 10 additions & 0 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
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 94de1d1

Please sign in to comment.