Home > Back-end >  How to post an array of values using `UrlFetchApp.fetch` with `application/x-www-form-urlencoded`?
How to post an array of values using `UrlFetchApp.fetch` with `application/x-www-form-urlencoded`?

Time:03-25

I fail to post an array of values unless I provide the array key. (see the output in my code)

Could someone tell the proper way to post an array with application/x-www-form-urlencoded?

function test() {
  function post(payload) {
    const url = 'https://my.php.post.server/';
    // Content of PHP: var_dump($_POST['tags']);
    const options = {
      'method': 'POST',
      'payload': payload
    }
    const response = UrlFetchApp.fetch(url, options);
    const content = response.getContentText();
    console.log(content);
  }

  post({
    'tags': [1, 2]
  });
  // string(28) "[Ljava.lang.Object;@71c0475b"

  post({
    'tags[]': [1, 2]
  });
  // array(1) {
  //   [0]=>
  //   string(27) "[Ljava.lang.Object;@9bc5c1d"
  // }

  post({
    'tags': 1,
    'tags': 2
  });
  // string(3) "2.0"
  
  post({
    'tags[]': 1,
    'tags[]': 2
  });
  // array(1) {
  //   [0]=>
  //   string(3) "2.0"
  // }

  post({
    'tags[0]': 1,
    'tags[1]': 2
  });
  // array(2) {
  //   [1]=>
  //   string(3) "2.0"
  //   [0]=>
  //   string(3) "1.0"
  // }
}

CodePudding user response:

In your situation, from your provided document, I proposed the following modification.

From your provided document, I found the following sample curl command.

curl https://pi.pardot.com/api/email/version/4/do/send \
--header "Authorization: Bearer <ACCESS TOKEN>" \
--header'Pardot-Business-Unit-Id: <BUSINESS UNIT ID>'
--data-urlencode campaign_id=12345 \
--data-urlencode from_assigned_user=1 \
--data-urlencode email_template_id=6789 \
--data-urlencode list_ids[]=123 \
--data-urlencode list_ids[]=456 \
--data-urlencode list_ids[]=789 \
--data-urlencode list_ids[]=101 \
--data-urlencode suppression_list_ids[]=987 \
--data-urlencode suppression_list_ids[]=654 \
--data-urlencode tags[]=new_prospect_email \
--data-urlencode tags[]=cart_abandoned \
--data-urlencode tags[]=subtotal_over_200 \
--data-urlencode scheduled_time=2021-10-31T17:00:00-0400 \
--data-urlencode format=json

In this case, I thought that when you want to use {'tags[]': [1, 2]}, it is required to request as the form data by the content type of application/x-www-form-urlencoded. In order to achieve this using Google Apps Script, how about the following modification?

Modified script:

In this modification, in order to convert the object of {'tags[]': [1, 2]} to the query parameter, I used this sample script.

function test() {
  // This is from https://tanaikech.github.io/2018/07/12/adding-query-parameters-to-url-using-google-apps-script/
  String.prototype.addQuery = function(obj) {
    return this   Object.keys(obj).reduce(function(p, e, i) {
      return p   (i == 0 ? "?" : "&")  
        (Array.isArray(obj[e]) ? obj[e].reduce(function(str, f, j) {
          return str   e   "="   encodeURIComponent(f)   (j != obj[e].length - 1 ? "&" : "")
        },"") : e   "="   encodeURIComponent(obj[e]));
    },"");
  }

  function post(payload) {
    const url = 'https://my.php.post.server/';
    // Content of PHP: var_dump($_POST['tags']);
    const options = {
      'method': 'POST',
      'payload': "".addQuery(payload).replace("?", ""),
    }
    const response = UrlFetchApp.fetch(url, options);
    const content = response.getContentText();
    console.log(content);
  }

  post({"tags[]": [1, 2]});
}
  • By this modification, {"tags[]": [1, 2]} is sent as the form data.

Note:

  • This is a simple sample script to explain for achieving your goal. Please modify this for your situation.

  • When addQuery is modified to your situation, it becomes as follows.

      const convertQuery = obj => Object.keys(obj).reduce((p, e) =>
        p   (Array.isArray(obj[e]) ? obj[e].reduce((str, f, j) =>
          str   e   "="   encodeURIComponent(f)   (j != obj[e].length - 1 ? "&" : ""),"") : e   "="   encodeURIComponent(obj[e])) ,"");
    
      function post(payload) {
        const url = 'https://my.php.post.server/';
        // Content of PHP: var_dump($_POST['tags']);
        const options = {
          'method': 'POST',
          'payload': convertQuery(payload)
        }
        const response = UrlFetchApp.fetch(url, options);
        const content = response.getContentText();
        console.log(content);
      }
    
      post({"tags[]": [1, 2]});
    
  • Related