I'm trying to sort my spreadsheet after a doGet. Is that possible?

77 views
Skip to first unread message

John Cutter

unread,
May 8, 2023, 4:07:40 PM5/8/23
to Google Apps Script Community
The code below takes input data (name and score) through URL parameters and inserts them into a Google Sheet (along with a timestamp). After inserting the data, it is then supposed to sort the sheet by the score column (column B).

The code below is successfully adding scores to my sheet, but the sort isn't working. I've even been using chatGPT (4.0) to try to solve this but none of its suggestions have worked. Any ideas?

var SHEET_NAME = "Sheet1";
var SCRIPT_PROP = PropertiesService.getScriptProperties(); // new property service

function setup() {
    var doc = SpreadsheetApp.getActiveSpreadsheet();
    SCRIPT_PROP.setProperty("key", doc.getId());
}

function doGet(e){
  return handleResponse(e);
}

function handleResponse(e) {
  var lock = LockService.getPublicLock();
  lock.waitLock(30000);
 
  try {
    var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
    var sheet = doc.getSheetByName(SHEET_NAME);

    var nextRow = sheet.getLastRow()+1;
 
    sheet.getRange(nextRow, 1).setValue(e.parameter["name"]);
    sheet.getRange(nextRow, 2).setValue(e.parameter["score"]);
    sheet.getRange(nextRow, 3).setValue(new Date());

    // Call the sortData function after inserting new data
    sortData();

    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();
  }
}

// New function to sort the data
function sortData() {
  var doc = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = doc.getSheetByName(SHEET_NAME);
  var rangeToSort = sheet.getRange(2, 1, sheet.getLastRow() - 1, 3);
  rangeToSort.sort({column: 2, ascending: true});
}

Tanaike

unread,
May 8, 2023, 9:55:07 PM5/8/23
to Google Apps Script Community
I think that your script works. But, you say "but the sort isn't working". In this case, how about redeploying your Web Apps and testing it again? If you want to keep the same URL of Web Apps by reflecting the latest script in Web Apps, this post might be useful. https://gist.github.com/tanaikech/ebf92d8f427d02d53989d6c3464a9c43

Reply all
Reply to author
Forward
0 new messages