Home > other >  How can I change how this code is being handled in a try catch block?
How can I change how this code is being handled in a try catch block?

Time:03-29

So I have this HTML form that takes user input and sends it to a Google Sheet. This is done through the following JavaScript code:

const sheetName = 'Sheet1'
const scriptProp = PropertiesService.getScriptProperties()

function initialSetup () {
  const activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet()
  scriptProp.setProperty('key', activeSpreadsheet.getId())
}

function doPost (e) {
  const lock = LockService.getScriptLock()
  lock.tryLock(10000)

  try {
    const doc = SpreadsheetApp.openById(scriptProp.getProperty('key'))
    const sheet = doc.getSheetByName(sheetName)

    const headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0]
    const nextRow = sheet.getLastRow()   1

    const newRow = headers.map(function(header) {
      return header === 'Date' ? 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()
  }
}

When the user submits the form, there are taken to a new link that shows the following:

Correct User submission

If there is an error, they are also taken to a new link with a similar message, that shows this:

{ 'result': 'error', 'error': e }

How can I change the contents of a code to simply show a JavaScrip alert like: alert('Data has been sent!') or alert('Oops. An error occurred...').

I am assuming this would take place in:

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

And:

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

HTML Form:

    <form 
  method="POST" 
  action="https://script.google.com/macros/s/AKfycby_xq-vLOZD0cXzN0vvvNYG40GK5yde0HYQD9IUq3FGGTcDggk3kG9QkmtBFSg037Le/exec"
>
  <input name="Job" type="text" placeholder="Job" required>
  <input name="Name" type="text" placeholder="Name" required>
  <button type="submit">Send</button>
</form>

Sample alert:

Sample Alert

Apologies if the wording of the question is off.

CodePudding user response:

let text = "Type what you want";
return ContentService
      .createTextOutput(JSON.stringify({"message":text}));
      .setMimeType(ContentService.MimeType.JSON)

CodePudding user response:

I believe your current situation and your goal are as follows.

  • From your reply of the HTML form is located in a separate Visual Studio Code file. The JavaScript code in my post is located in the Apps Script online editor., I understood that your HTML is put out of Google Apps Script project.

  • You want to submit the values from the HTML form to your Web Apps.

  • After the values were sent to Web Apps, you want to open an alert on the client side.

In this case, how about the following modification?

Modified script:

In this modification, your HTML is modified as follows. Before you use this script, please set your Web Apps URL to url. In this case, your Google Apps Script is not required to be modified.

<form>
  <input name="Job" type="text" placeholder="Job" required>
  <input name="Name" type="text" placeholder="Name" required>
  <button type="submit" onclick="sample(this);return false;">Send</button>
</form>

<script>
  function sample(e) {

    const url = "https://script.google.com/macros/s/###/exec"; // Please set your Web Apps URL.

    const obj = [...e.parentNode].reduce((o, f) => (o[f.name] = f.value, o), {});
    const query = new URLSearchParams(obj); 
    fetch(url   "?"   query, { method: "POST" })
      .then((res) => res.json())
      .then((res) => {
        console.log(res);
        alert(res.result);
      });
  }
</script>
  • In this modification, when the form is submitted, the values are sent to Web Apps using fetch. And, after the values were sent, the returned value is retrieved and an alert is opened.

Note:

  • Although in your question, the setting of Web Apps is not included, from your HTML, I guessed that the setting of Web Apps is Execute as: Me and Who has access to the app: Anyone (using new IDE). Please be careful about this.

  • This modified scrupt supposes that your Google Apps Script works fine. Please be careful this.

Reference:

  • Related