From 4e04d1910285798f513c238a2fb6b466da12b5e7 Mon Sep 17 00:00:00 2001 From: Dominik Heidler Date: Fri, 13 Sep 2024 14:12:02 +0200 Subject: [PATCH] Replace $.ajax() with fetch() Ticket: https://progress.opensuse.org/issues/166310 Co-authored-by: Martchus --- assets/javascripts/comments.js | 98 +++++++++++++++++----------------- assets/javascripts/openqa.js | 10 ++++ assets/javascripts/tests.js | 17 +++--- 3 files changed, 67 insertions(+), 58 deletions(-) diff --git a/assets/javascripts/comments.js b/assets/javascripts/comments.js index 8121045f8f3c..3f47fcafa163 100644 --- a/assets/javascripts/comments.js +++ b/assets/javascripts/comments.js @@ -51,15 +51,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) { @@ -75,31 +75,27 @@ function updateComment(form) { displayElements([textElement, form.applyChanges, form.discardChanges], 'none'); markdownElement.style.display = ''; markdownElement.innerHTML = 'Loading…'; - $.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) { @@ -109,22 +105,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]; @@ -136,12 +136,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()}); + }) + .catch(error => { + window.alert(`The comment couldn't be added: ${error}`); + }); } function insertTemplate(button) { diff --git a/assets/javascripts/openqa.js b/assets/javascripts/openqa.js index dd4de2be52c9..ff505a4d2bb1 100644 --- a/assets/javascripts/openqa.js +++ b/assets/javascripts/openqa.js @@ -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' ? '' + text + '' : text; } diff --git a/assets/javascripts/tests.js b/assets/javascripts/tests.js index 724572533150..93b8894aa012 100644 --- a/assets/javascripts/tests.js +++ b/assets/javascripts/tests.js @@ -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) {