forked from UKSOURCE/cms.hailearning.edu.vn
63 lines
1.9 KiB
JavaScript
63 lines
1.9 KiB
JavaScript
/**
|
|
* Global Admin Scripts
|
|
*/
|
|
|
|
console.log('CMS Admin Main JS loaded');
|
|
|
|
// Helper to show toast notifications
|
|
function showToast(title, message, type = 'info') {
|
|
if (typeof window.showToast === 'function') return window.showToast(title, message, type);
|
|
console.log(`[${type.toUpperCase()}] ${title}: ${message}`);
|
|
}
|
|
|
|
// Helper to handle AJAX form submissions with optional confirmation and loading state
|
|
window.handleFormAjax = async (formEl, options = {}) => {
|
|
const {
|
|
confirmMessage = null,
|
|
onSuccess = null,
|
|
onError = null,
|
|
loaderBtn = null
|
|
} = options;
|
|
|
|
if (confirmMessage && !confirm(confirmMessage)) {
|
|
return false;
|
|
}
|
|
|
|
const formData = new FormData(formEl);
|
|
const data = Object.fromEntries(formData.entries());
|
|
const originalBtnHtml = loaderBtn ? loaderBtn.innerHTML : null;
|
|
|
|
try {
|
|
if (loaderBtn) {
|
|
loaderBtn.disabled = true;
|
|
loaderBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Processing...';
|
|
}
|
|
|
|
const response = await fetch(formEl.action, {
|
|
method: formEl.method || 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json'
|
|
},
|
|
body: JSON.stringify(data)
|
|
});
|
|
|
|
const result = await response.json();
|
|
|
|
if (result.success) {
|
|
if (onSuccess) onSuccess(result);
|
|
else showToast('Success', result.message || 'Operation successful', 'success');
|
|
} else {
|
|
if (onError) onError(result);
|
|
else showToast('Error', result.message || 'Operation failed', 'error');
|
|
}
|
|
} catch (error) {
|
|
console.error('AJAX Error:', error);
|
|
showToast('Error', 'A network error occurred', 'error');
|
|
} finally {
|
|
if (loaderBtn) {
|
|
loaderBtn.disabled = false;
|
|
loaderBtn.innerHTML = originalBtnHtml;
|
|
}
|
|
}
|
|
};
|