Search code examples
javascriptgoogle-apps-scriptgoogle-sheetsweb-applications

Checking sheets field if some data exists using macro script


Somebody who is an expert in Macro script in sheet help me with my code. I tried with this approach in macro script

var sheetName = 'records';
var scriptProp = PropertiesService.getScriptProperties();

function intialSetup() {
  var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  scriptProp.setProperty('key', activeSpreadsheet.getId());
}

function usernameExists(username) {
  var doc = SpreadsheetApp.openById(scriptProp.getProperty('key'));
  var sheet = doc.getSheetByName(sheetName);
  var dataToCheck = username.toLowerCase();

  var values = sheet.getRange("A:A").getValues();

  for (var i = 0; i < values.length; i++) {
    var cellData = values[i][0].toString().toLowerCase();
    if (cellData === dataToCheck) {
      return true;
    }
  }
  return false;
}

function doPost(e) {
  var lock = LockService.getScriptLock()
  lock.tryLock(10000)
  
  var doc = SpreadsheetApp.openById(scriptProp.getProperty('key'));
  var sheet = doc.getSheetByName(sheetName);

  // var postData = JSON.parse(e.postData.contents);
  // var usernameToCheck = postData['username'];
  // var usernameToCheck = e.parameter.username;
  var usernameToCheck = e.parameter['username']

  if (usernameExists(usernameToCheck)) {
    return ContentService
      .createTextOutput(JSON.stringify({ 'result': 'error', 'error': 'Username already exists' }))
      .setMimeType(ContentService.MimeType.JSON);
  }

  try {
    var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
    var nextRow = sheet.getLastRow() + 1;

    var newRow = headers.map(function (header) {
      return header === 'timestamp' ? new Date() : e.parameter[header];
    });

    sheet.getRange(nextRow, 1, 1, newRow.length).setValues([newRow]);

    return ContentService
      .createTextOutput(JSON.stringify({ 'result': 'success', 'row': nextRow }))
      .setMimeType(ContentService.MimeType.JSON);
  }
  
  catch (e) {
    return ContentService
      .createTextOutput(JSON.stringify({ 'result': 'error', 'error': e }))
      .setMimeType(ContentService.MimeType.JSON);
  }

  finally {
    lock.releaseLock()
  }
}

The goal is to check the incoming data if it exists on the sheet in column A which is the 'username' field, when exists skip the saving process. I even tried to use the postData but still save the data if it exists. I also created a test function that works, but it's not working in actual data using javascript it's not working. Here is my test function

function checker() {
  if (usernameExists('userTest')) {
    Logger.log("Username already exists.");
  } else {
    Logger.log("Username doesn't exist.");
  }
}

I tried also the convert the parameter to string using usernameToCheck.toString()

Here's my code in javascript file

var form = document.getElementById('myForm');
function submitForm() {
    fetch(scriptURL, { method: 'POST', body: new FormData(form)})
        .then(response => showSuccessMessage(response))
        .catch(error => showErrorMessage(error))
}

This is my second day in debugging. Or is this doable?


Solution

  • Problem solved! Here's what I did. adding a parameter in the post request solved the problem, I added
    fetch(scriptURL+'?username=' + usernameToCheck.value, { method: 'POST', body: formData})
    my only problem before was getting the value of the username from here
    var usernameToCheck = e.parameter['username']
    after adding the parameter I changed line
    var usernameToCheck = e.parameter['username']
    to
    var usernameToCheck = e.parameter.username

    Thank you so much for taking the time to share your idea; it inspired me to come up with a solution.