Tree
Tree

Reputation: 31

Any idea why this post request won't work?

I am trying to send this information into a webhook, but the webhook isn't catching the second post method I am attempting. The first one works. Obviously, the "API QUERY" and the "ID" in the webhook contain custom variables. Can you tell me why it is? I know that the if statement itself works because it will log the information that I need.

function myFunction() {

  var data = {
  'name': 'Bob Smith',
  'age': 35,
  'pets': ['fido', 'fluffy']
};
var options = {
  'method' : 'post',
  'contentType': 'application/json',
  // Convert the JavaScript object to a JSON string.
  'payload' : JSON.stringify(data)
};
UrlFetchApp.fetch('https://hooks.zapier.com/hooks/catch/Id/Id/', options);

  var res = UrlFetchApp.fetch("API QUERY GOES HERE")
   
  
var content = res.getContentText();

var json = JSON.parse(content);

var gratuityAmount = 17

for (i=0; i<json.items.length; i++){
  
  var orderName = json["items"][i]["name"];
  var orderId = json["items"][i]["id"];


  // Write an if statment that says "if the variable orderName contains "ezCater Order", then continue, all else stop

  if (orderName.includes("ThisOrder")) {

    var options = {
      'method': 'post',
      'contentType': 'application/json',
      'payload': JSON.stringify(orderName, orderId, gratuityAmount)
    };
    UrlFetchApp.fetch('https://hooks.zapier.com/hooks/catch/Id/Id/', options)
  };

  };
}

Upvotes: 0

Views: 68

Answers (1)

Tanaike
Tanaike

Reputation: 201603

From your provided information, I understood your situation as follows.

  • Value of json is like { "items": [ { "id": 5788549471, "name": "My job name"},,,]}.
  • You want to use var orderName = json["items"][i]["name"];, var orderId = json["items"][i]["id"]; and var gratuityAmount = 17 as payload = { orderName, orderId, gratuityAmount } in the loop.

In this case, it is required to modify 'payload': JSON.stringify(orderName, orderId, gratuityAmount).

Because the arguments of JSON.stringify is JSON.stringify(value, replacer, space). In your script of 'payload': JSON.stringify(orderName, orderId, gratuityAmount), the 1st argument is put as the value. By this, only the value orderName is returned. I think that this is the reason for your issue.

If you want to use 'payload': JSON.stringify(orderName, orderId, gratuityAmount) as payload = { orderName, orderId, gratuityAmount } in the loop, please modify as follows.

From:

'payload': JSON.stringify(orderName, orderId, gratuityAmount)

To:

'payload': JSON.stringify({orderName, orderId, gratuityAmount})
  • By this, {orderName, orderId, gratuityAmount} is used as {orderName: orderName, orderId: orderId, gratuityAmount: gratuityAmount}. Ref

References:

Upvotes: 1

Related Questions