Josh's Changes

This commit is contained in:
2026-04-03 20:43:00 -04:00
parent df06dcc0d7
commit 03825c1048
16 changed files with 216 additions and 54 deletions
+39 -5
View File
@@ -8,6 +8,30 @@
var apiBase = typeof window.familyHubApiBase === 'string' ? window.familyHubApiBase : '/api';
/**
* Avoids JSON.parse on empty bodies (Firefox: "unexpected end of data at line 1 column 1")
* and surfaces clearer errors when PHP returns HTML or nothing.
*/
function parseJsonResponseText(res, text) {
var trimmed = (text || '').trim();
if (trimmed === '') {
var emptyErr = new Error(
!res.ok ? (res.statusText || 'Request failed') : 'Empty response from server.'
);
emptyErr.payload = {};
emptyErr.status = res.status;
throw emptyErr;
}
try {
return JSON.parse(trimmed);
} catch (e) {
var parseErr = new Error('Server did not return JSON. Check server logs or network tab.');
parseErr.payload = trimmed.slice(0, 500);
parseErr.status = res.status;
throw parseErr;
}
}
function postJson(path, body) {
return fetch(apiBase + path, {
method: 'POST',
@@ -15,7 +39,8 @@
credentials: 'same-origin',
body: JSON.stringify(body || {})
}).then(function (res) {
return res.json().then(function (data) {
return res.text().then(function (text) {
var data = parseJsonResponseText(res, text);
if (!res.ok) {
var err = new Error(data.error || res.statusText || 'Request failed');
err.payload = data;
@@ -775,11 +800,15 @@
function readMealsLibrary() {
var el = document.getElementById('mealsLibraryJson');
if (!el || !el.textContent) {
if (!el) {
return [];
}
var raw = (el.textContent || '').trim();
if (raw === '') {
return [];
}
try {
return JSON.parse(el.textContent);
return JSON.parse(raw);
} catch (e) {
return [];
}
@@ -1032,7 +1061,8 @@
var safeId = String(mealId);
fetch(apiBase + '/meal_export.php?mealId=' + encodeURIComponent(safeId), { credentials: 'same-origin' })
.then(function (res) {
return res.json().then(function (data) {
return res.text().then(function (text) {
var data = parseJsonResponseText(res, text);
return { res: res, data: data };
});
})
@@ -1083,7 +1113,11 @@
var reader = new FileReader();
reader.onload = function () {
try {
mealImportParsed = JSON.parse(String(reader.result || ''));
var raw = String(reader.result || '').trim();
if (raw === '') {
throw new Error('File is empty.');
}
mealImportParsed = JSON.parse(raw);
$prev.text(JSON.stringify(mealImportParsed, null, 2));
$('#btnMealImportSubmit').prop('disabled', false);
if ($fb.length) {