Search code examples
google-apps-scriptweb-applicationsquery-string

Something wrong with my QueryString is not working


The below code is working perfectly with me:

fileID = "xxxxxxD_kjE7gzYE3WAcGdxaQEEQNReY"
sheetName = "Data"
barcode=6287029390129
function doGet(e) {
  // barcode = e.queryString.barcode;
  // Open Google Sheet using ID
  var ss = SpreadsheetApp.openById(fileID);
  var sheet = ss.getSheetByName(sheetName);
  // Read all data rows from Google Sheet
  const values = sheet.getRange(2, 1, sheet.getLastRow() - 1, sheet.getLastColumn()).getValues();

const letterToColumn = letter => {
  let column = 0,
    length = letter.length;
  for (let i = 0; i < length; i++) {
    column += (letter.charCodeAt(i) - 64) * Math.pow(26, length - i - 1);
  }
  return column;
};

const columnLetters = ["N", "X", "S"]; // Column letters you want to retrieve.
const fields = values.map(r => columnLetters.map(e => r[letterToColumn(e) - 1]));

const selected = fields.filter(line => line[0].toString() == barcode);

// Converts data rows in json format
const result = JSON.stringify({ItemCode: selected[0],SupplierName:selected[1],BarcCode:selected[2],});

// Returns Result
return ContentService.createTextOutput(result).setMimeType(ContentService.MimeType.JSON);
}

And it is giving the proper output here: https://script.googleusercontent.com/macros/echo?user_content_key=O8c8_XtQiEf2rj1KJmJ-M10DeZdZNBwC1BIJmMkKWrUKEcSmryaVP2vgzhZ36OUjQG-f0TWG2dHj2dYoWxVxSrgw-DiBa4B8m5_BxDlH2jW0nuo2oDemN9CCS2h10ox_1xSncGQajx_ryfhECjZEnJ46GsyZpwpQML1JY8e2mFM6PA9fUavbC9NlAUdPQJJZCeWnt48yaEub6ks_JLupvGj3mrFbAM7LJLzMpb8DzxfdXKW5dFehmNz9Jw9Md8uu&lib=MLHrKBCgdUSV7iELS76RttSiyBt1bEuOL

Then I'm trying make barcode dynamic, so it is provided with the url, and read as e.queryString, so uncommeted the e.queryString and replaced:

// barcode = e.queryString.barcode;

By

 barcode = e.queryString.barcode;

And provided the new query as:

https://script.google.com/macros/s/.../exec?barcode=6287029390129

so the long url be: https://script.google.com/macros/s/AKfycbwd00m1t2h6h6D58vrGHRboOvYoyeiUb-pXcWexPxQDLbvLmW3HAkHomBU_HM-crcTOzw/exec?barcode=6287029390129

But it is giving me empty object {}


Solution

  • e.queryString gives you the whole query part of the url as a string.

    If you want to extract the value from a key-value pair in the query string, use the request parameter e.parameter

    Sample:

    function doGet(e) {
      console.log("e.parameter: " + JSON.stringify(e.parameter));
      barcode = e.parameter.barcode;
      console.log("barcode: " + barcode);
    }