ExtJs, how to send JSON on store.load() using POST method - json

I need to send JSON object during read operation on store. Headers and method are set correctly.
var proxyDefinition = {
type : 'rest',
api : {
read : '/some/url'
},
actionMethods : {
create : 'POST',
read : 'POST',
update : 'PUT',
destroy : 'DELETE'
},
reader : {
type : 'json'
}
};
var store = Ext.create('Ext.data.Store', {
proxy : proxyDefinition,
model : 'SomeModel'
});
// this needs to send JSON
store.load({
params : {
filter: [] // some filtering rules
}
});
Problem is that POST body is sent as url encoded query string, not JSON object with property "filter".
ExtJs version 4.2.2

It is likely that you are looking for proxy config option paramsAsJson:true

Related

Slack API call to postMessage not working

I'm just trying to make a simple postMessage call from a google apps script with an image attached, but I get the following response:
"{"ok":false,"error":"invalid_arg_name"}"
Here is the function that creates the payload:
function getPostMessagePayload(fileUrl) {
var content = {
"channel":"#data-vis",
"token": ACCESS_TOKEN,
"text":"Chart update:",
"attachments": [
{
"title": "Chart",
"fallback": "Fallback",
"text": "Testing chart",
"image_url": fileUrl
}
]
};
return content;
}
And here is where I make the request:
var POST_MESSAGE_ENDPOINT = 'https://slack.com/api/chat.postMessage';
function performPostMessage(payload) {
var res = UrlFetchApp.fetch(
POST_MESSAGE_ENDPOINT,
{
method: "post",
payload: JSON.stringify(payload),
muteHttpExceptions: true,
}).getContentText();
return res;
}
It's impossible to tell what the actual problem is. I've tried making my token obviously incorrect, the URL obviously incorrect, and deleting/adding random args and it gives the same response every time.
When I use the webhook to do this rather than the API, it works fine.
My app has the following permissions in Slack:
chat:write:bot
incoming-webhook
Problem
You are sending a JSON object as payload with your POST request, whilst the contentType parameter of the fetch() method is defaulted to application/x-www-form-urlencoded.
Solution 1
In addition to JSON.stringify(), to ensure the payload is sent correctly, wrap it in an encodeURIComponent() built-in function. If the issue persists, continue to solution 2.
Update to solution 1
Nearly forgot how fetch() method treats objects passed to payload with default x-www-form-urlencoded content type. Remove the JSON.stringify() entirely (and add encodeURI() / encodeURIComponent() if needed).
Solution 2
Slack API supports application/json content type of POST requests. In your case it might be easier to send the request with contentType parameter set to application.json (note that you will have to move authorization from payload to headers):
//fetch part;
var res = UrlFetchApp.fetch(
POST_MESSAGE_ENDPOINT,
{
method : 'post',
contentType : 'application/json',
headers : {
Authorization : 'Bearer ' + ACCESS_TOKEN
},
payload : JSON.stringify(payload),
muteHttpExceptions : true,
})
//payload part;
var payload = {
"channel" : "#data-vis",
"text" : "Chart update:",
"attachments" : [
{
"title" : "Chart",
"fallback" : "Fallback",
"text" : "Testing chart",
"image_url" : fileUrl
}
]
};
Useful links
fetch() method reference;
postMessage method reference (Slack API);

extjs error on filling store

I have a java map. I converted it to json string and I obtain something like this :
{"NEW ZEALAND":"111111111111111","CHAD":"1","MOROCCO":"111","LATVIA":"11"}
Now I want to use it in a store and then a chart like the following code but it's not working. I have no error just no display.
var obj = Ext.Ajax.request({
url: App.rootPath + '/controller/home/dashboard/test.json',
method:'GET',
success: function(response) {
return Ext.JSON.decode(response.responseText);
}
});
var store2 = Ext.create('Ext.data.Store', {
model: 'PopulationPoint',
data: obj
});
Ext.create('Ext.chart.Chart', {
renderTo: 'infos2',
width: 500,
height: 300,
store: store2,
series: [
{
type: 'pie',
field: 'population',
label: {
field: 'state',
display: 'rotate',
font: '12px Arial'
}
}
]
});
The AJAX request is asynchronous. As such, the obj variable used to initialize your data won't contain your data yet.
One option is to create the store2 variable and create the chart directly in the success callback of the AJAX request.
A cleaner option would be to configure the store with a proxy to load the url, and in the callback create the chart.
EDIT
The JSON response does not contain the fields that are declared in your model (sent in the comments). Update the JSON to return a properly formatted model and the chart should work as seen in this fiddle. The JSON should look something like
[
{
"state" : "New Zealand",
"population" : 111111111
},
{
"state" : "Chad",
"population" : 1
}
]

Post JSON from express to external server

I want to be able to post JSON to another server directly from node (using express). Basically, I don't want to expose my api keys when calling different api's but still be able to call the service.
This is what I'm trying to do, but from the server instead of the client:
https://github.com/GetResponse/DevZone/blob/master/API/examples/javascript_synopsis.html
JS from client that I want to implement:
var api_key = 'ENTER_YOUR_API_KEY_HERE';
// API 2.x URL
var api_url = 'http://api2.getresponse.com';
function add_contact() {
var campaigns = {};
// find campaign named 'test'
$.ajax({
url : api_url,
data : JSON.stringify({
'jsonrpc' : '2.0',
'method' : 'get_campaigns',
'params' : [
api_key,
{
// find by name literally
'name' : { 'EQUALS' : 'test' }
}
],
'id' : 1
}),
type : 'POST',
contentType : 'application/json',
dataType : 'JSON',
crossDomain : true,
async : false,
success : function(response) {
// uncomment following line to preview Response
// alert(JSON.stringify(response));
campaigns = response.result;
}
});
// because there can be only (too much HIGHLANDER movie) one campaign of this name
// first key is the CAMPAIGN_ID required by next method
// (this ID is constant and should be cached for future use)
var CAMPAIGN_ID;
for(var key in campaigns) {
CAMPAIGN_ID = key;
break;
}
$.ajax({
url : api_url,
data : JSON.stringify({
'jsonrpc' : '2.0',
'method' : 'add_contact',
'params' : [
api_key,
{
// identifier of 'test' campaign
'campaign' : CAMPAIGN_ID,
// basic info
'name' : 'Test',
'email' : 'test#test.test',
// custom fields
'customs' : [
{
'name' : 'likes_to_drink',
'content' : 'tea'
},
{
'name' : 'likes_to_eat',
'content' : 'steak'
}
]
}
],
'id' : 2
}),
type : 'POST',
contentType : 'application/json',
dataType : 'JSON',
crossDomain : true,
async : false,
success : function(response)
{
// uncomment following line to preview Response
// alert(JSON.stringify(response));
alert('Contact added');
}
});
}
I think your node server can act as a proxy to the third party server for your client requests.
Your server can collect all the input parameters needed for api call, say add_contact. Your node server, who has right credentials to access the 3rd party server, makes the api call, and passes on the response received to the client.
You can make use of built in http library in node, or the request module (more convenient) to make these calls.
Basically, you need to make a wrapper for the external apis you need, and you're all set.
I hope it helps.
Node.js provides an API for HTTP requests similar to jQuery's AJAX-API:
http://nodejs.org/api/http.html#http_http_request_options_callback

How to send a JSON payload with UrlFetchApp service?

I'm trying to POST to a web service that is expecting to get JSON as payload using Google Apps Script. I'm using the following code:
var options =
{
"method" : "post",
"contentType" : "application/json",
"headers" : {
"Authorization" : "Basic <Base64 of user:password>"
},
"payload" : { "endDate": "2012-06-03" }
};
var response = UrlFetchApp.fetch("http://www.example.com/service/expecting/json", options);
On the server side I'm getting the following error:
WARN [facade.SettingsServlet] 04 Jun 2012 15:30:26 - Unable to parse request body: endDate=2012-06-03
net.liftweb.json.JsonParser$ParseException: unknown token e
I'm assuming that the server is expecting to get
{ "endDate": "2012-06-03" }
instead of
endDate=2012-06-03
but I don't know how to make the UrlFetchApp do it.
I do not understand the server side error but the 'payload' parameter must be a string as specified here: https://developers.google.com/apps-script/class_urlfetchapp?hl=fr-FR#fetch.
try:
var options =
{
"method" : "post",
"contentType" : "application/json",
"headers" : {
"Authorization" : "Basic <Base64 of user:password>"
},
"payload" : '{ "endDate": "2012-06-03" }'
};
If you set payload as a String, it will be passed directly (as a
UTF-8 string).
If you set payload as an Object, it will be sent like
an HTML form (which means either 'application/x-www-form-urlencoded' if the
fields are simple, or 'multipart/form-data' if the Object includes a
blob/file).
For your use case (the server is expecting to receive JSON), it sounds like Utilities.jsonStringify() is the way to go.
Something like this worked for me in a similar situation:
Instead of creating payload and adding to options, I built the parameters into a string to append to the URL:
var params = "id=2179853&price=62755";
then, I appended params to the url string:
var result = UrlFetchApp.getRequest(url + '?' + params, options);
So, my options was passed containing only the header.
For my project, this worked like a charm.
Here goes the code that should work with some important comments:
function testMe() {
var products_authkey = "------------";
try {
var url = "https://app.ecwid.com/api/v1/---------/product?id=----------&secure_auth_key=" + products_authkey;
//url= "http://requestb.in/----------"; // you can actually debug what you send out with PUTs or POSTs using Requestb.in service
var payload = {
id: "21798583", // id is necessary and should be a string, or it might be sent in scientific representation (with E)
price: 62755
};
payload = JSON.stringify(payload); // the payload needs to be sent as a string, so we need this
var options = {
method: "put",
contentType: "application/json", // contentType property was mistyped as ContentType - case matters
payload: payload
};
var result = UrlFetchApp.getRequest(url, options);
Logger.log(result) // a better way to debug
var result = UrlFetchApp.fetch(url, options); // works perfectly in my case
Logger.log(result)
} catch (e) {
Logger.log(e)
}
}

loading data from json in sencha

I am creating an application where i have created a list and populated the data in the list using a data store.
data.js
Ext.regModel('Contact', {
fields: ['firstName', 'lastName', 'DOB', 'group']
});
iPolis.ListStore = new Ext.data.Store({
model: 'Contact',
sorters: 'lastName',
getGroupString : function(record) {
return record.get('group');
},
data: [
{ firstName: "Domino", lastName: "Derval" , DOB: "28May2008", group:"Personalize"},
]
});
This part of the code runs fine where i get the data and display it. Now what i require is a connection to the database and retriving the data in the data.js using a json file.
Any suggestions on how thats possible?
iPolis.ListStore = new Ext.data.Store({
model : 'Contact',
proxy : {
type : 'ajax',
url : 'js/person_list.json',
reader : {
type : 'json',
//root : 'results',
// totalCount : 'total'
}
},
autoLoad : true
});
used this for getting the data but it gives me an error sayin XMLHttprequest cannot load data in file.json
Go through the Ext.data.Proxy in Sencha API and also check the examples of store in API docs.
Just replace the url property of reader to the php file.
return proper JSON