Google Script - Call APi - Error object - javascript

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();

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.

How to solve error parsing in dataTables?

I have a function button that carry user info fullname, after clicking the button, it will send fullname and level to an API to be process and the result should be display in dataTable. Unfortunately, I got this error.
This is console.log for console.log(params). {"task_level":3,"fullname":"Administrator"}
Below is console.log for console.log(params).
Both console log is similar to API's result.
I don't know which is proper.
JS 1st Try (1st Ajax to send the parameter to API and after return success hopefully working but not.
"<button type='button' class='btn btn-dark btn-round' onclick='viewTablePerson(""+value.fullname+"")'>View Project</button>"+
function viewTablePerson(fullname){
var level = 3;
var fullname2 = fullname;
var obj = {
task_level : level,
fullname : fullname2
};
var params = JSON.stringify(obj);
console.log(params)
$.ajax({
url : url_api + '/api/user_task',
crossDomain: true,
type : 'POST',
dataType : 'json',
data: params,
success: function(response){
if (response.status == "Success"){
console.log(response)
$('#viewProgress').DataTable({
ajax: {
url: url_api + '/api/user_task',
crossDomain : true,
type : "POST",
cache : false,
dataType : "json",
contentType: false,
processData: true,
data : params,
timeout: 10000,
},
destroy: true,
columns: [
{ data : "task_name"},
{ data : "task_owner"},
{ data : "task_status"}
],
});
}
},
error: function(e){}
});
}
JS 2nd Try
<button type='button' class='btn btn-dark btn-round' onclick='viewTablePerson(""+value.fullname+"")'>View Project</button>"+
function viewTablePerson(fullname){
var level = 3;
var fullname2 = fullname;
var obj = {
task_level : level,
fullname : fullname2
};
var params = JSON.stringify(obj);
console.log(params)
$('#viewProgress').DataTable({
ajax: {
url: url_api + '/api/user_task',
crossDomain : true,
type : "POST",
cache : false,
dataType : "json",
contentType: false,
processData: true,
data : params,
timeout: 10000,
},
destroy: true,
columns: [
{ data : "task_name"},
{ data : "task_owner"},
{ data : "task_status"}
],
});
}
Documentation says:
When using the ajax option to load data for DataTables, a general error can be triggered if the server responds with anything other than a valid HTTP 2xx response.
So, you have to check server-side response instead of search for problems on the front-end.
Also, in your case make sure
the plugin sends request to the same domain from which the current page is loaded;
browser security system doesn't prevent loading of external scripts - for example on http://localhost you cannot Ajax load a script from http://google.com without special measures;
you are specifying a relative path without a domain name (if you are using a single domain);
JSON data in response is a valid.
If you cannot alter the backend system to fix the error, but don't want your end users to see the alert message, you can change DataTables' error reporting mechanism to throw a Javascript error to the browser's console, rather than alerting it:
$.fn.dataTable.ext.errMode = 'throw';

How to use element name when initializing object in javascript?

I'm trying to get data using ajax function, but my code returns :
Uncaught SyntaxError: unexpected string..
Javascript :
var myParams = {
$('#csrf').attr('name') : $('#csrf').val(),
'module' : 'culinary',
'id' : '12',
}
$.ajax({
url: '/uploader/get_list',
type: 'GET',
data: myParams,
success: function(response) {
reponse = $.parseJSON(response);
console.log(response);
}
});
One of my friends suggested to use this:
var myParams = [];
myParams[$('#csrf').attr('name')] = $('#csrf').val();
myParams['module'] = 'culinary';
myParams['id'] = '12';
But if I use the second method, the PHP function can't recognize the parameters.
What's the correct way to send parameters to an ajax function?
The issue is in your creation of the myParams object. To create a key using a variable you need to use bracket notation. Try this:
var myParams = {
'module': 'culinary',
'id': '12',
}
myParams[$('#csrf').attr('name')] = $('#csrf').val();
The second example you have doesn't work because you create an array, ie. [], not an object, {}.
Also note that if you set the dataType property of the request then you don't need to manually parse the response as jQuery will do it for you:
$.ajax({
url: '/uploader/get_list',
type: 'GET',
data: myParams,
dataType: 'json',
success: function(response) {
console.log(response);
}
});
You should define new object {} and not new array [] :
var myParams = [];
Should be :
var myParams = {};
Hope this helps.

AngularJS http post not working

I have created a service and I using that for my login:
EDIT: Added the 'success' and 'error' code.
EDIT 2: I am developing an iOS mobile application which includes Javascript/AngularJS. So is there a way to view errors as alerts..
.service('Login', function($http, $q, $httpParamSerializerJQLike) {
return {
loginUser: function(ipAdd, name, pw) {
var sendurl = 'http://' + ipAdd + ':8080/loginuser/user.cgi';
var postData = {
'ACTION' : 'login',
'LOGIN' : name,
'PASSWORD' : pw
};
//what is the mistake here?
return $http({
method : 'POST',
url : sendurl,
data : $httpParamSerializerJQLike(postData),
headers : { 'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(response) {
var x2js = new X2JS();
var jsonObj = x2js.xml_str2json(response.data);
if (typeof jsonObj === 'object') {
alert("here:1");
return jsonObj;
} else {
alert("here:2");
// invalid response
return $q.reject(jsonObj);
}
}).error(function(response) {
//do error
//comes here when no internet connection is found..
alert("here:3");
return $q.reject(response.data);
});
}
}
})
I have also included this in app.js:
var app = angular.module("myApp", ['starter.services'],function($httpProvider){
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
});
My actual url looks like this:
'http://' + ipAdd + ':8080/loginuser/user.cgi?ACTION=login&LOGIN=' + name + '&PASSWORD=' + pw;
I have tried this approach too: https://stackoverflow.com/a/25570077/5876598
My service is not returning anything..
I want to know if I'm doing mistake in my url formation, or while sending data.
Thanks.
The best way to know where the mistake comes from is to check the 'network' tab on your navigator developer console.
Assuming you are runing on linux or mac, you can also try to use CURL to have an idea of what return the url you are trying to reach.
We can't help you with the code only.
I added a deferred promise in my service.
I also changed "success().error()" to ".then(function(data, status, headers, config){}) . Don't know why it didn't work when I used success and error.
Actually previously I noticed some issue while rendering promise itself in service. Follow the below structure
.service('Login', function($http, $q, $httpParamSerializerJQLike) {
return {
loginUser: function(ipAdd, name, pw) {
var sendurl = 'http://' + ipAdd + ':8080/loginuser/user.cgi';
var postData = {
'ACTION' : 'login',
'LOGIN' : name,
'PASSWORD' : pw
};
//what is the mistake here?
return $http({
method : 'POST',
url : sendurl,
data : $httpParamSerializerJQLike(postData),
headers : { 'Content-Type': 'application/x-www-form-urlencoded'}
});
}
}
})
.controller('SomeCtrlName',function(Login){
//pass your parameter to below service.
Login.loginUser().then(function success(){
//write success code here
},function error(){
//write error code here
)};
})

How to extract data from url fetch response

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);

Categories

Resources