How to extract data from url fetch response - javascript

I implemented a fetch method using Google Script and it returns me the following log:
[16-06-10 14:06:03:942 EEST] {
"accessToken": "data",
"userId": 3096,
"created": "2016-06-10T05:06:03.799-06:00"
}
Does anyone know how can I extract the value from accessToken ?
Here is my gs code:
var url = "https://example.com"
var payload = {
'username' : "user",
'password' : "pass",
}
var options = {
'method' : 'post',
'payload': JSON.stringify(payload),
};
var urlResponse = UrlFetchApp.fetch(url, options);
Logger.log(urlResponse); //this returns me the log shown above
Basically I want to add the "data" value from accessToken to a variable getData.

I think that even if the variable urlResponse look to be an object it will only return you some string value. You should try to do something like that:
var data = JSON.parse(urlResponse.getContentText());
Logger.log(data.accessToken);

Related

blank gravity form entries with API

I'm trying to create an entry in a Gravity form via API post in Google Apps script.
An entry gets created but the values are showing blank. any insight of where I'm possibly going wrong would be appreciated.
Below is my code:
function gravityForms(){
const url = 'https://example.com/wp-json/gf/v2/forms/18/entries';
const payload = [{"2":"My name"}];
const options = {
"method" : "post",
"payload" : JSON.stringify(payload),
"muteHttpExceptions" : true
};
options.headers = {
"Content-Type" : "application/json",
"Authorization" : "Basic " + Utilities.base64Encode("ck_xxxxxxxxxxxx:cs_xxxxxxxxxxxxxxxxxx")
};
const res = UrlFetchApp.fetch(url, options);
console.log(res.getContentText());
}
This is the response I get back in the logger
{"0":{"2":"My name"},"form_id":18,"id":3320}
I removed the [] from the entry object and it worked. funny since the examples show to add them.

Javascript ajax how to show just a value of array

I am newbie in javascript and need some help :( I am simply using post api in my html page like this
varsettings = {
"url": "https://credimax.gateway.mastercard.com/api/nvp/version/54",
"method": "POST",
"timeout": 0,
"headers": {
"Content-Type": "application/x-www-form-urlencoded",
"Cookie": "TS01f8f5b8=0163461fdde5ee3588241a8b83c8806a36a236cc1484715206aeee58f05ff4acc21bff27c0f22f45d8027bdfa3ef1b330efc711746"
},
"data": {
"apiOperation": "CREATE_CHECKOUT_SESSION",
"apiPassword": "asdasdasdsad",
"apiUsername": "merchant.sadasda",
"merchant": "asdasda",
"interaction.operation": "AUTHORIZE",
"order.id": "121312327",
"order.amount": "0.01",
"order.currency": "BHD"
}
};
$.ajax(varsettings).done(function(response) {
console.log(response);
});
Its showing responsei n console correctly like this
merchant=E10561950&result=SUCCESS&session.id=SESSION0002247374303I6654970F90&session.updateStatus=SUCCESS&session.version=18a5ad4401&successIndicator=5f04c5071d2f46fd
I want to just console the session.id from response how can i do this ?
i try with with console.log(response.session.id) but its not showing
Please try this:
<script>
$.ajax(varsettings).done(function (response) {
let items = response.split('&');
let sessionIDText = items[2];
let sessionIDParts = sessionIDText.split('=');
let sessionID = sessionIDParts[1]
console.log(sessionID);
});
</script>
or simply :
sessionID = response.split('&')[2].split('=')[1];
You have received a string back from the server that needs to be decoded into an object before you can work with it. Try obj = decodeURIComponent(response) and see if you can work with the resulting obj

Google Script - Call APi - Error object

I'm doing a URL call in a API but I've got this error
TypeError: Cannot find function getContentText in object
Here is bellow my code.
I even tried to encode the URL but still not working.
Could you please tell me where I'm wrong ? And what is the fix ?
Thank you,
var url = 'https://welcome.de.coremetrics.com/analyticswebapp/api/1.0/report-data/explore/explore.ftlid=634022';
var params = {
'clientId': 'mi_id',
'format': 'JSON',
'userAuthKey' : 'my_key',
'language' : 'en_US',
'viewID' : 'default.ftl',
'period_a' : 'D20170601',
'fileName' : 'explore_explore^id=634022_default_view_D20170601.json'
}
var options = {
'method' : 'GET',
'payload' : params
};
response = UrlFetchApp.getRequest(url,options);
var data = JSON.parse(response.getContentText());
Solution found:
res = encodeURI(query)
response = UrlFetchApp.fetch(res, {muteHttpExceptions: true, escaping: false}).getContentText();

I'm sending POST to my webservice from postman and from my JS code - the response differ, why?

I have a webservice that returns a json based on input parameters.
In the software called POSTMAN I'm sending data with the following parameters:
{"deleted": "false", "nsfwPosts": "false", "anonymousPosts": "true", "publicContent": "true", "friendsNames": ""}
It gives me the desired result.
However, when I do it again, this time from my code:
var params = {};
params["nsfwPosts"] = false;
params["publicContent"] = true;
params["deleted"] = false;
params["anonymousPosts"] = true;
params["friendsNames"] = ""
console.log(params);
$.ajax({
type: 'POST',
url: 'http://mywebservice.com/...',
contentType: "application/json",
dataType: 'json',
data : JSON.stringify(params)
}).success(function (response) {
console.log(response);
then the console log brings empty result. What might be the problem here?
In first case you are sending true/false values as string. In second case they are Boolean.
Do like this
var params = {};
params["nsfwPosts"] = "false";
params["publicContent"] = "true";
params["deleted"] = "false";
params["anonymousPosts"] = "true";
params["friendsNames"] = ""

Insert variable value into ajax post data

I have created a form with textboxes and a dropdown menu, inside my code I've created a script which will be called when clicking "Send Form"
Lets say my field are : firstName, lastName, country (dropdown)
Here is the script:
function f1() {
var settings = {
"async": true,
"url": "https://api.TheSite.com/v2/applications/123456789/newJson.json",
"method": "POST",
"headers": {
"x-api-key": "123456789123456",
"content-type": "application/json",
},
"processData": false,
"data": "{\r\n \"deployment\": {\r\n \"revision\": \"string\",\r\n \"changelog\": \"string\",\r\n \"description\": \"string\",\r\n \"user\": \"string\"\r\n }\r\n}"
}
$.ajax(settings).done(function(response) {
console.log(response);
alert("The Form Was Sent");
});
}
I would like to insert those 3 variables' values inside the "data" string like so:
"data": "{\r\n \"deployment\": {\r\n \"revision\": \`firstName
\",\r\n \"changelog\": \"`lastName
and so on...
In the dropdown menu, I assume it will be displayed as an array. How do I include my variable inside?
First create an empty object and insert the data into it.
Next use JSON.strigify() to convert that into a JSON blob before you send it over to the server.
var data = {};
data.deployment = {};
data.deployment.revision = firstName;
data.deployment.changelog = lastName;
var settings = {
....,
data: JSON.stringify(data)
};
Since you are already using jQuery to perform your AJAX request, you should be aware that you can actually pass a native JavaScript object into the data portion of the request. You don't need to have it converted to a JSON string. If you want to, you can just stringify it.
You can actually establish default request options and then merge them with the data you want to request.
var defaults = {
url: 'https://api.TheSite.com/v2/applications/123456789/newJson.json',
method: 'POST',
contentType: 'application/json',
headers: {
'x-api-key': '123456789123456',
},
processData: false,
async: true
};
function makeXhrRequest(config) {
var xhrRequest = $.extend(true, defaults, config);
// If you want to convert the request to a json String.
//xhrRequest.data = JSON.stringify(data);
$.ajax(xhrRequest).done(function(data, textStatus, jqXHR) {
console.log(data);
alert("The Form was sent...");
});
}
var $myForm = $('form[name="my-form"]');
makeXhrRequest({
data : {
deployment : {
revision : $myForm.find('input[name="firstname"]').val(),
changelog : $myForm.find('input[name="lastname"]').val(),
description : 'string',
user : 'string'
}
}
});
SOLVED
this is the syntax that worked for me +$("#firstName")[0].value+ and this is the code :
"data":"{\r\n\deployment\: {\r\n revision\:"+"\""+$("#firstName")[0].value+"\","+"\r\n"

Categories

Resources