I’m using Google Apps Script withSuccessHandler() and even if the logs from Logger are all correct, after returning from the function in the backend, the result is always a null.
Here’s reported the code block where I call the google.script.run.withSuccessHandler() referring to the function checkBarcode().
// Check if the vessel exists
function checkVessel() {
const barcode = document.getElementById("barcode").value.trim();
barcode.toString();
if (!barcode) {
alert("Please scan or enter a barcode.");
return;
}
console.log("Sending barcode to server:", barcode); // Debugging
google.script.run.withSuccessHandler(result => {
console.log("Result received from server:", result); // Debugging
showForm(result);;
}).checkBarcode(barcode)
}
Here’s reported the function checkBarcode (also the function findBarcode used in checkBarcode).
// Check if a vessel with the barcode exists
function checkBarcode(barcode) {
barcode.toString().trim();
Logger.log("Checking barcode: " + barcode);
// Search for barcode in N2 sheet
const n2Result = findBarcode("N2", barcode);
if (n2Result) {
Logger.log("Barcode found in N2.");
return result = {
sheet: "N2",
row: n2Result.row,
data: n2Result.data,
};
}
// Search for barcode in N2O sheet
const n2oResult = findBarcode("N2O", barcode);
if (n2oResult) {
Logger.log("Barcode found in N2O.");
return result = {
sheet: "N2O",
row: n2oResult.row,
data: n2oResult.data,
};
}
// If not found in any sheet
Logger.log("Barcode not found in any sheet.");
return result = null; // Return null explicitly if not found
}
// Find barcode in a sheet
function findBarcode(sheetName, barcode) {
const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
const sheet = spreadsheet.getSheetByName(sheetName);
if (!sheet) {
Logger.log("Sheet not found: " + sheetName);
return null;
}
const data = sheet.getDataRange().getValues();
Logger.log("Data in sheet " + sheetName + ": " + JSON.stringify(data));
for (let i = 0; i < data.length; i++) {
Logger.log("Comparing: " + data[i][0].toString().trim() + " with " + barcode.toString().trim());
if (data[i][0].toString().trim() === barcode.toString().trim()) {
return { row: i + 1, data: data[i] }; // Return row index and data
}
}
return null; // Not found
}
I tried to avoid using multiple function in the .gs file but the results were the same. I also tried to convert the barcode variable in string (probably too many times) to avoid errors.