简体   繁体   中英

My HTTP POST in javascript isn't running my function in my google apps script

I have been trying for a couple hours now to see if I can send POST DATA to a google apps script web app. I'm attempting to make my data that's sent send me an email. But when i run my code no errors appear. Just nothing happens.

Here is my html, it's just a button to run the function

<!DOCTYPE html>
<html>
<head>
    <!--Import JQUERY-->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"</script>
    <script src="script.js"></script>
</head>

<body>
    <button type="button" onclick="submitClicked()">submit</button>
</body>
</html>

Here is my javascript meant to send the request

function submitClicked() {
    sendData();
}

function sendData() {
    console.log("running");

    const url = "https://script.google.com/a/macros/limitlessflight.com/s/AKfycbyAhx3wCRR4fS30ZrVpFpe-lxksRjn8ZWTUmTj5YlbmD8wG2PlzzXzDNUUaS8ntu09LBQ/exec";
    var xhr = new XMLHttpRequest();
    xhr.open("POST", url, true);
    xhr.send(JSON.stringify({
        value: "hello"
    }));
    
    console.log("done");
}

And here is my apps script code to send an email. When i run this code by itself, or entering the page it works correctly. I added the doGet(e) function, just so I could test if a GET request would work instead.

function doPost(e) {
  emailForm(e);
}

function doGet(e) {
  emailForm(e);
}

function emailForm(data) {
    MailApp.sendEmail({
        to: "youremailhere@emailhere.com",
        subject: "Test Email",
        htmlBody: data
      });
}

Your Google Apps Script web application is incomplete as the doPost and doGet functions don't return one of the required objects. From Requirements for web apps

  • The function returns an HTML service HtmlOutput object or a Content service TextOutput object.

A simple fix is to add return ContentService.createTextOutput('Success;'); to the end of each of these functions:

function doPost(e) {
  emailForm(e);
  return ContentService.createTextOutput('Success!');
}


function doGet(e) {
  emailForm(e);
  return ContentService.createTextOutput('Success!');  
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM