Skip to content
Merged
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
73 changes: 11 additions & 62 deletions jslib/lorisFetch.js
Original file line number Diff line number Diff line change
@@ -1,80 +1,29 @@
/**
* Display the login modal when a request returns a 401 response.
*/
function handleUnauthorized() {
if (typeof window === 'undefined') {
return;
}
if (!window.$ || !window.loris) {
return;
}

const $ = window.$;
if (!$('#login-modal').length) {
return;
}

if ($('#login-modal').hasClass('in')) {
$('#login-modal-error').show();
return;
}

$('#login-modal').modal('show');
$('#modal-login')
.off('click.lorisFetch')
.on('click.lorisFetch', function(e) {
e.preventDefault();
let data = {
username: $('#modal-username').val(),
password: $('#modal-password').val(),
login: 'Login',
};

fetch(window.loris.BaseURL, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
},
body: new URLSearchParams(data),
credentials: 'same-origin',
})
.then((response) => {
if (!response.ok) {
throw new Error('request_failed');
}
$('#login-modal-error').hide();
$('#login-modal').modal('hide');
})
.catch(() => {
$('#login-modal-error').show();
});
});
}

/**
* Wrapper around fetch that keeps credentials and handles 401s.
* Wrapper around fetch that keeps credentials on same-origin requests.
*
* The global helper in loris-scripts.js owns login modal handling for 401s.
* Bundled modules import this file to use that shared helper when it exists.
*
* @param {*} input
* @param {object=} init
* @return {Promise<Response>}
*/
function lorisFetch(input, init) {
function fallbackFetch(input, init) {
const options = Object.assign(
{
credentials: 'same-origin',
},
init || {}
);

return fetch(input, options).then((response) => {
if (response.status === 401) {
handleUnauthorized();
}
return response;
});
return fetch(input, options);
}

if (typeof window !== 'undefined') {
const lorisFetch = typeof window !== 'undefined' && window.lorisFetch
? window.lorisFetch
: fallbackFetch;

if (typeof window !== 'undefined' && !window.lorisFetch) {
window.lorisFetch = lorisFetch;
}

Expand Down
92 changes: 57 additions & 35 deletions modules/configuration/js/cohort.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
$(document).ready(function() {
"use strict";
var lorisFetch = window.lorisFetch;
$('div').tooltip();
$(".savecohort").click(function(e) {
var form = $(e.currentTarget).closest('form');
Expand All @@ -11,48 +12,69 @@ $(document).ready(function() {
var recruitmentTarget = $(form.find(".cohortRecruitmentTarget")).val();
e.preventDefault();

$.ajax(
{
"type" : "post",
"url" : loris.BaseURL + "/configuration/ajax/updateCohort.php",
"data" : {
lorisFetch(loris.BaseURL + "/configuration/ajax/updateCohort.php", {
method: "post",
headers: {
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
},
body: new URLSearchParams({
"cohortID" : cohortID,
"title" : title,
"useEDC" : useEDC,
"WindowDifference" : windowDifference,
"RecruitmentTarget" : recruitmentTarget,
},
"dataType": "json",
"success" : function(data) {
$(form.find(".saveStatus"))
.text(data.ok)
.css({ 'color': 'green'})
.fadeIn(500)
.delay(1000);
if (cohortID === 'new') {
setTimeout(function(){
location.reload();
}, 1000);
} else {
var projectDiv = document.getElementById(`#cohort${cohortID}`);
var Name = projectDiv.innerText;
projectDiv.innerText = title;
var projectHeader = document.getElementById(`cohort${cohortID}`);
projectHeader.children[0].innerText = title + projectHeader.children[0].innerText.substring(
Name.length
);
}
},
"error" : function(data) {
$(form.find(".saveStatus"))
.text(data.responseJSON.error)
.css({ 'color': 'red'})
.fadeIn(500)
.delay(1000);
}),
credentials: "same-origin",
})
.then(async function(response) {
var text = await response.text();
var data = null;
try {
data = JSON.parse(text);
} catch (err) {
data = null;
}
if (!response.ok) {
throw new Error(
(data && data.error) ? data.error : 'Request failed.'
);
}
Comment thread
Montekkundan marked this conversation as resolved.
}
$(form.find(".saveStatus"))
.text(data && data.ok ? data.ok : "Saved")
.css({ 'color': 'green'})
.fadeIn(500)
.delay(1000);
if (cohortID === 'new') {
setTimeout(function(){
location.reload();
}, 1000);
} else {
var projectTab = document.querySelector(`a[href="#cohort${cohortID}"]`);
var projectHeader = document.getElementById(`cohort${cohortID}`);

);
if (projectHeader && projectHeader.children.length > 0) {
var headerTitle = projectHeader.children[0].innerText;
var suffix = projectTab
? headerTitle.substring(projectTab.innerText.length)
: '';
projectHeader.children[0].innerText = title + suffix;
}

if (projectTab) {
projectTab.innerText = title;
}
}
})
.catch(function(error) {
var message = error && error.message
? error.message
: 'Request failed.';
$(form.find(".saveStatus"))
.text(message)
.css({ 'color': 'red'})
.fadeIn(500)
.delay(1000);
});


});
Expand Down
55 changes: 34 additions & 21 deletions modules/configuration/jsx/configuration_helper.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import i18n from 'I18nSetup';
import swal from 'sweetalert2';
import lorisFetch from 'jslib/lorisFetch';

$(function() {
const {t} = i18n;
Expand Down Expand Up @@ -67,11 +68,17 @@ $(function() {
let id = $(this).attr('name');
let button = this;

$.ajax({
type: 'post',
url: loris.BaseURL + '/configuration/ajax/process.php',
data: {remove: id},
success: function() {
lorisFetch(loris.BaseURL + '/configuration/ajax/process.php', {
method: 'post',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
},
body: new URLSearchParams({remove: id}),
})
.then((response) => {
if (!response.ok) {
throw new Error('request_failed');
}
if ($(button)
.parent().parent().parent().children()
.length > 1
Expand All @@ -91,12 +98,10 @@ $(function() {
.addClass('remove-new')
.removeClass('btn-remove');
}
},
error: function(xhr, desc, err) {
console.error(xhr);
console.error('Details: ' + desc + '\nError:' + err);
},
});
})
.catch((err) => {
console.error(err);
});
}
});
});
Expand All @@ -110,11 +115,20 @@ $(function() {
// Clear previous feedback
$('.submit-area > label').remove();

$.ajax({
type: 'post',
url: loris.BaseURL + '/configuration/ajax/process.php',
data: form,
success: function() {
lorisFetch(loris.BaseURL + '/configuration/ajax/process.php', {
method: 'post',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
},
body: form,
})
.then(async (response) => {
if (!response.ok) {
let text = await response.text();
let error = new Error('request_failed');
error.lorisMessage = text;
throw error;
}
let html = '<label>' + t(
'Submitted',
{ns: 'configuration'}
Expand All @@ -124,12 +138,11 @@ $(function() {
.appendTo('.submit-area')
.fadeIn(500).delay(1000).fadeOut(500);
location.reload();
},
error: function(xhr, desc, err) {
let html = '<label>' + xhr.responseText + '</label>';
})
.catch((error) => {
let html = '<label>' + (error.lorisMessage || '') + '</label>';
$(html).hide().appendTo('.submit-area').fadeIn(500).delay(1000);
},
});
});
});

// On form reset, to delete the elements added with the "Add field" button that were not submitted.
Expand Down
Loading