kkkttc
kkkttc

Reputation: 29

POST method in Google Apps Script

May I ask what is wrong when I use the POST method in the Apps script?

function myFunctionpost() {
  var url = "mydomain.com/2spreadsheet.php";
  var data = { "testpost" : " Text text text" };
   var payload = JSON.stringify(data);

 var headers = { "Accept":"application/json", 
                "contentType" : "application/json",
              "Authorization":"Basic _authcode_"
             };

 var options = { "method":"POST",
             "contentType" : "application/json",
            "headers": headers,
                "payload" : payload
           };

  var response = UrlFetchApp.fetch(url ,options);
  Logger.log(response );  
 }

The myFunctionpost() in the Apps script is about posting the Json data : "testpost" to the url.

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    echo "Server is requested";

    if(isset($_POST["testpost"])){
      echo "Post something here";
      echo $_POST["testpost"];
    }
}

And the code in (2spreadsheet.php) showing that I want to post the data I posted, but it does not work.

The Loggin Output:

[15-07-12 14:06:00:205 HKT]

Server is requested

Can anyone tell me what is the problem?

Upvotes: 1

Views: 1399

Answers (1)

piscator
piscator

Reputation: 8719

You don't have to specify the content type and can leave out JSON.Stringify. Your object data is already a JavaScript object. It will be interpreted as an HTML form.

var url = "mydomain.com/2spreadsheet.php";
var data = { "testpost" : " Text text text" };

var options = { "method":"POST",
                "payload" : data
};

var response = UrlFetchApp.fetch(url ,options);
Logger.log(response ); 

The content type will default to application/x-www-form-urlencoded. You can check this with $_SERVER["CONTENT_TYPE"].

Upvotes: 2

Related Questions