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?
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"].
Related
I'm trying to fire a plugin request from my ICN plugin. The request goes as below. However, I'm getting a 403 Forbidden error from the server.
Forbidden
You don't have permission to access /navigator/jaxrs/plugin on this server.
https://<icnserver.com>/navigator/jaxrs/plugin?repositoryId=Demo&query=%5B%7B%22name%22%3A%22ID%22%2C%22operator%22%3A%22LIKE%22%2C%22values%22%3A%5B%22123434234%22%2C%22%22%5D%7D%5D&className=Checks&plugin=DemoPlugin&action=DemoService&desktop=Demo
Plugin JS:
aspect.around(ecm.model.SearchTemplate.prototype, "_searchCompleted", function advisingFunction(original_searchCompleted){
return function(response, callback, teamspace){
var args = [];
var templateName = response.templates[0].template_name;
var res = response;
var requestParams = {};
requestParams.repositoryId = this.repository.id;
requestParams.query = query;
requestParams.className = templateName;
Request.invokePluginService("DemoPlugin", "DemoService",
{
requestParams: requestParams,
requestCompleteCallback: lang.hitch(this, function(resp) { // success
res.rows = resp.rows;
res.num_results = resp.rows.length;
res.totalCount = resp.rows.length;
args.push(res);
args.push(callback);
args.push(teamspace);
original_searchCompleted.apply(this,args);
})
}
);
}
});
You need to provide a security_token to be able to call your service, so you need to login first.
Then, open your browser's debug and check the requests in the network tab.
There you can see that every request that targets the /navigator/jaxrs/* URI will contain it, so something like this will be among the headers:
security_token: 163594541620199174
So my bet is that you have not set it in your client (I recommend a postman to test your service, or I would add a test (ICN) feature page in the ICN plugin project in order to be able to call it properly). In your feature page, you can call your service directly using the ecm/model/Request OOTB navigator dojo/javascript class, as you can see in CheckinAction.js:
_checkInDocument: function (item, requestData)
{
var self = this;
var payLoadObject = {requestType: "Get", id: item.id};
Request.postPluginService("DocuSignPlugin", "UpdateSignedDocumentService", "application/json", {
requestParams: {
repositoryId : item.repository.id,
serverType : item.repository.type,
docId : item.docid,
envelopeId: item.attributes.DSEnvelopeID,
payLoad: json.stringify(payLoadObject)
},
requestCompleteCallback: function(response) {
if (response.returncode == 0)
{
item.attributeDisplayValues.DSSignatureStatus = "Checkedin";
item.attributes.DSSignatureStatus = 4;
item.update(item);
}
else if (response.returncode == -1)
{
items = [];
items.push(item);
self._showLoginDialog(items);
}
},
backgroundRequest : false,
requestFailedCallback: function(errorResponse) {
// ignore handline failures
}
});
},
As you can see, you don't have to add the security_token to the requestParams, the framework will do it for you.
I'm trying to learn how to query for data from a local government data site (hoping I can teach my math students to do some data analysis). I'm hoping to get the data and insert them into Google Sheets. The following is a sample provided by the official site on how to do a query:
var data = {
resource_id: '1b702208-44bf-4829-b620-4615ee19b57c', // the resource id
limit: 5, // get 5 results
q: 'jones' // query for 'jones'
};
$.ajax({
url: 'https://data.gov.sg/api/action/datastore_search',
data: data,
dataType: 'jsonp',
success: function(data) {
alert('Total results found: ' + data.result.total)
}
});$
I tried the following code in Google Apps Script:
function testapi(){
var data = {
resource_id: '1b702208-44bf-4829-b620-4615ee19b57c', // the resource id
limit: 5, // get 5 results
q: 'Yishun'
};
var url = "https://data.gov.sg/api/action/datastore_search";
var response = UrlFetchApp.fetch(url,data).getContentText();
}
I receive a 404 error. I think the option "data" was not passed.
Would appreciate some help. I am a math teacher, not a coding expert.
Update: I changed the code to this but still 404 error.
function testapi(){
var data = {
resource_id: '1b702208-44bf-4829-b620-4615ee19b57c', // the resource id
limit: 5, // get 5 results
q: 'Yishun' // query for 'jones'
};
var options = {
'method' : 'post',
'contentType': 'application/json',
'payload' : JSON.stringify(data)
};
var url = "https://data.gov.sg/api/action/datastore_search";
var response = UrlFetchApp.fetch(url,options).getContentText();
}
Issue:
Whenever payload key is present in options/params argument of UrlFetchApp, the method is set to post by default. And any attempt to change the method to get is "silently" ignored. Other similar scripting platforms automatically convert the payload to url query parameters. But, UrlFetchApp silently changes the method to post and nothing else.
Solution:
Re-create the data object as a query string. For example, data:{x:1,y:2} should be changed to ?x=1&y=2 and appended to url.
Snippet:
function testapi() {
var options = {
method: 'get',
// 'contentType': 'application/json',
// 'payload' : data,//If set, method is ignored.
headers: { Accept: '*/*', 'Content-Type': 'application/json' },
muteHttpExceptions: true,
};
var url = 'https://data.gov.sg/api/action/datastore_search';
//var url = 'https://httpbin.org/get'; test the method
function objectToQueryParams(obj) {
return (
'?' +
Object.entries(obj)
.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
.join('&')
);
}
var data = {
resource_id: '1b702208-44bf-4829-b620-4615ee19b57c', // the resource id
limit: 5, // get 5 results
q: 'Yishun', // query for 'Yishun'
};
var query = objectToQueryParams(data);
url += query;
var response = UrlFetchApp.fetch(url, options).getContentText();
Logger.log(response);
}
function objectToQueryParams(obj) {
return (
'?' +
Object.entries(obj)
.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
.join('&')
);
}
var data = {
resource_id: '1b702208-44bf-4829-b620-4615ee19b57c', // the resource id
limit: 5, // get 5 results
q: 'Yishun', // query for 'jones'
};
console.log(objectToQueryParams(data));
Related:
UrlSearchParams
I am sending form data in JSON & serialize format to golang server using ajax. I am not able to read those data.
I am using kataras/iris golang framework.
Below is my code -
(function ($) {
$.fn.serializeFormJSON = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
})(jQuery);
var Contact = {
sendMessage: function() {
return m.request({
method: "POST",
url: "/send/message",
data: JSON.stringify(jQuery('#contact-form').serializeFormJSON()),
withCredentials: true,
headers: {
'X-CSRF-Token': 'token_here'
}
})
}
}
<!-- Data looks like below, what is sent -->
"{\"first_name\":\"SDSDFSJ\",\"csrf.Token\":\"FjtWs7UFqC4mPlZU\",\"last_name\":\"KJDHKFSDJFH\",\"email\":\"DJFHKSDJFH#KJHFSF.COM\"}"
And I am trying to fetch the data from server using below code -
// Contact form
type Contact struct {
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Email string `json:"email"`
}
contact := Contact{}
contact.FirstName = ctx.FormValue("first_name")
contact.LastName = ctx.FormValue("last_name")
contact.Email = ctx.FormValue("email")
ctx.Writef("%v", ctx.ReadForm(contact))
My all data is blank, How to grab the data? I am using https://github.com/kataras/iris golang framework.
One the one hand, you are sending a JSON to the server, but when fetching the parameters you are fetching them as "application/x-www-form-urlencoded", first, send the JSON parameters as JSON and not as string, remove the stringifying, i.e:
instead of:
JSON.stringify(jQuery('#contact-form').serializeFormJSON())
do:
jQuery('#contact-form').serializeFormJSON()
and in your Go file, bind it to your object:
var contact []Contact
err := ctx.ReadJSON(&contact)
good luck :)
I am trying to intercept all requests, before send, from an Extjs App, POST and GET and then manipulate the URL and add a new Header, Authorization: Bearer XYZ123.
I've this code:
Ext.data.Connection.override({
request: function (options) {
var me = this;
this.cors = true;
this.useDefaultHeader = false;
this.useDefaultXhrHeader = false;
options.headers = { "Authorization": "Bearer VAROIS1iOiJKV1QiLCJh" };
var separator = options.url.indexOf('/') == 0 ? "" : "/";
options.url = UrlAPIPrefix + separator + options.url;
return me.callOverridden(arguments);
}
});
But when i try to use it, the Header Authorization is not sent in both cases, GET and POST. Parameters are not sent when using POST. I am able to see params if debugging the code into Extjs files, but can't see it on chrome Request Headers, see image.
If any one knows how to do it, in one place, i will be glad if you can help me.
That's because Ext.Ajax - the singleton of Ext.data.Connection - is used for most requests in the framework and overriding the latter does not affect the former. This overriding behavior was changed in extjs 5 and is intended by Sencha.
Use what you need of this instead:
Ext.Ajax.setWithCredentials(true);
Ext.Ajax.on({
beforerequest: function(conn, options) {
options.headers = options.headers || {};
options.headers['Authorization'] = 'Bearer VAROIS1iOiJKV1QiLCJh';
},
requestexception: function(conn, response, options) {
Ext.Error.raise('...');
}
});
And don't hardcode the token into your javascript!!!
Instead of overriding the class, i created a bootstrap class to set up the ajax interceptor. Called Bootstrap.init() in Application.launch() method.
Ext.define('MyApp.Bootstrap', {
singleton : true,
init: function() {
Ext.Ajax.on({
beforerequest: function(conn, opts){
if(opts.url && Ext.String.startsWith(opts.url, '/')) {
return;
}
if(opts.url && !Ext.String.startsWith(opts.url, MyApp.Config.SERVER_CONTEXT)) {
opts.url = MyApp.Config.SERVER_CONTEXT + opts.url;
}
var clientId = MyApp.getApplication().clientId;
opts.headers = Ext.apply({'X-Client-Id': clientId}, opts.headers);
Ext.log('Sending Request to : ', opts.url);
}
});
}
});
For my app I have a long running task that generates stats. I would like the stats to be available to my users as a json file. Is there a way using parse to store the results of the task as a json that my users can retrieve? It would be great if there was some server side caching that I could take advantage of as well.
UPDATE
The following code takes my array of dictionaries and saves it as a file. I am now trying to store the file as part of a table called Cache. However the result is
Input: {}
Result: undefined
The code snippet looks like
var Buffer = require('buffer').Buffer;
...
var json = <array of dictionaries>;
var jsonStr = JSON.stringify(json);
var buf = new Buffer(jsonStr, 'utf8');
var json64 = buf.toString('base64');
var parseFile = new Parse.File('result', { "base64" : json64 }, 'application/json');
parseFile.save().then(function(parseFile) {
// The file has been saved to Parse.
var cache = new Cache();
attr = {};
attr['file'] = parseFile;
console.log(parseFile.url());
cache.save(attr, {
success : function(result) {
status.success("Cached");
},
error : function(result, error) {
status.error("Error: + " + error.message);
}
});
}, function(error) {
console.log(error);
status.error(error.message);
});