I want to make a HTTP-POST-Request with AJAX to call a JSON API. So, the API should return a response in JSON. I can see on the console of the API, that the request is successful. But the problem is, that no data or status is returned, or that I can't use it with JQuery. Here is my function:
$.post("http://api-adress/controller",
{
email: input_mail,
password: input_pw
},
function(data, status){
alert(data);
alert(status);
}, 'json');
I guess the problem is that the response from the Server does not get saved in the variables data and status correctly.
I would suggest to change a little bit your code like below:
var dataString = {
email: input_mail,
password: input_pw
}
$.post("http://api-adress/controller", dataString, function (result) {
})
.done(function (result) {
//Here is your result. You must parseJSON if it is json format
var data = jQuery.parseJSON(result);
})
.fail(function () {
//use this if you need it
})
Also make sure that you get the response through firebug in console tab. You can check there what you post, what you get etc.
Related
I have trouble storing a JSON file in my DynamoDB table with the help of my Lambda function and my API Gateway on AWS. I have the following piece of code which gets executed once I press a button on my HTML site:
$('#submit').on('click', function(){
var example = {"number":"121212"};
$.ajax({
type: 'POST',
url: API_URL,
data: JSON.stringify(example),
contentType: "application/json",
success: function(data){
location.reload();
}
});
return false;
});
When pressed the website reloads, hence I assume function has successfully executed. However my problem is that the data does not arrive in the correct format in the lambda function and hence does not execute properly. When checking in CloudWatch it is shown as { number: '121212' } instead of {"number":"121212"}. Any idea how I can make sure that the value 'arrives' has a valid JSON format in my Lambda function?
Here's my Lambda function:
exports.handler = function index(e, ctx, callback) {
var params = {
Item: { number: e.number },
TableName: 'collectionOfNumbers'
};
docCLient.put(params, function(err, data) {
if (err) {
callback(err, null);
} else {
callback(null, data);
}
});
}
If I'm reading this right, e.number is the value of the JSON parameter 'number' that you are passing in, e.g. '121212'. I'm making the assumption from the usage that docClient is putItem under the hood.
I think your Item param should look like:
Item: {"number": {N: e.number}}
See AWS Docs for info regarding PutItem https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_PutItem.html
I want to send multiple replies for a single user-triggered postback on Messenger. I've been following Messenger's developer documentation and couldn't really find how to do this.
My code structure is very similar to the tutorials they've given on the site, I have a 'handlePostback' function which identifies the received postback and compares it to a set of predefined payloads to find the 'response' JSON object. This response is given to 'callSendAPI' which puts this JSON object into the basic format of sending the message back to the Messenger API.
function handlePostback(sender_psid,receivedPostback)
{ if(payload== 'defined_payload') {
response = {
text: 'Some text'
};
callSendAPI(sender_psid,response);
}
function callSendAPI(sender_psid,response) {
let body = {
recipient: {
id= sender_psid
},
message: response
};
// Followed by code for POST request to the webhook
}
This being the basic structure, now I want to send multiple messages as a reply to one postback. I did some digging, and I found that the solution might be to create a message [] array. But how do I do this? Because my 'response' is being generated through that function, and the messages structure should look like this (I think):
let body = {
recipient: {
id=sender_psid
},
messages: [ {
response1
},
{
response2
}
]
};
I hope I could explain my question, please let me know if I can provide more details!
Nice question. If you are not familiar with Node.js the way to do it is not too obvious and this is not documented well on Facebook's Send API Documentation.
Firstly, your approach of sending multiple messages, using an array, as you may have observed won't work. Facebook has a solution for sending up to 100 API Calls with one request but in my opinion this is not needed in your situation. If you want to find out more about it check out the Batched Request Documentation, you'll find out that the implementation is different than yours.
One solution that will work is to call the callSendAPI function multiple times. But this solution has one major drawback: You won't be able to control the actual sequence of the messages sent. For example if you want to send two separate messages, you cannot guarantee which will be sent first to the user.
To solve this issue you need to chain your callSendAPI functions in a way that guarantees that the next callSendAPI call will happen only after the first message is already sent. You can do this in NodeJS by using either callbacks or promises. If you are not familiar with either of them, you can read this for callbacks and this for promises.
You'll need to modify your callSendAPI function and especially the part that sends the POST request to Facebook. I will present a solution to your issue by using promises and the module node-fetch.
const fetch = require('node-fetch');
function handlePostback(sender_psid,receivedPostback){
if (payload == 'defined_payload') {
response = {
text: 'Some text'
};
response2 = //... Another response
response3 = //... Another response
callSendAPI(sender_psid,response).then(() => {
return callSendAPI(sender_psid, response2).then(() => {
return callSendAPI(sender_psid, response3); // You can add as many calls as you want
});
});
}
}
function callSendAPI(sender_psid,response) {
let body = {
recipient: {
id= sender_psid
},
message: response
};
const qs = 'access_token=' + encodeURIComponent(FB_PAGE_TOKEN); // Here you'll need to add your PAGE TOKEN from Facebook
return fetch('https://graph.facebook.com/me/messages?' + qs, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(body),
});
}
I found the below link useful to sort out the way to implement multiple responses on single post back.
https://codingislove.com/build-facebook-chat-bot-javascript/
Like you said, array should work. Create an array variable with multiple response messages
var multipleResponse = {
messages: [{
response1
},
{
response2
}]
};
And push the array variable to your function
function callSendAPI(sender_psid,response) {
let body = {
recipient: {
id= sender_psid
},
message: []
};
// Followed by code for POST request to the webhook
}
Finally push the array to your function array
body.message.push(multipleResponse.messages);
#Christos Panagiotakopoulos. I am not getting my mainMenuResponse which is chained using then. Rather, i am getting response thrice.
handlePostback function =>
// Handles messaging_postbacks events
function handlePostback(sender_psid, received_postback) {
let response;
// Get the payload for the postback
let payload = received_postback.payload;
// Set the response based on the postback payload
if (payload === 'fashionTip') {
response = { "text": getFashionTip() } // calls a function which gives a fashion-tip
// Send the message to acknowledge the postback
callSendAPI(sender_psid, response).then(() => {
return callSendAPI(sender_psid, mainMenuResponse)
});
callSendAPI function =>
// Sends response messages via the Send API
function callSendAPI(sender_psid, response) {
// construct the message body
let request_body = {
"recipient": {
"id": sender_psid
},
"message": response
}
// Send the HTTP request to the messenger platform
request({
"uri": "https://graph.facebook.com/v2.6/me/messages",
"qs": {"access_token": PAGE_ACCESS_TOKEN},
"method": "POST",
"json": request_body
}, (err, res, body) => {
if (!err) {
console.log("Message sent!");
} else {
console.error("Unable to send mesage:" + err);
}
});
}
Don't modify callSendAPI function. In your handlePostback function call callSendAPI multiple times.
callsendAPI(sender_psid,response1);
callsendAPI(sender_psid,response2);
I want to call JSON data as much as the amount of data in the store. Here is the code:
storeASF.each(function(stores) {
var trano = stores.data['arf_no'];
Ext.Ajax.request({
results: 0,
url: '/default/home/getdataforeditasf/data2/'+trano+'/id/'+id,
method:'POST',
success: function(result, request){
var returnData = Ext.util.JSON.decode(result.responseText);
arraydata.push(returnData);
Ext.getCmp('save-list').enable();
Ext.getCmp('cancel-list').enable();
},
failure:function( action){
if(action.failureType == 'server'){
obj = Ext.util.JSON.decode(action.response.responseText);
Ext.Msg.alert('Error!', obj.errors.reason);
}else{
Ext.Msg.alert('Warning!', 'Server is unreachable : ' + action.response.responseText);
}
}
});
id++;
});
storeARF.loadData(arraydata);
StoreASF contains data[arf_no] which will be used as a parameter in Ajax request url. StoreASF could contain more than one set of the object store, so looping is possible. For every called JSON data from request would be put to array data, and after the looping is complete, I save it to storeARF with the loadData method.
The problem is, my data format is wrong since loadData can only read JSON type data. I already try JSON stringify and parse, but couldn't replicate the data format. Any suggestion how to do this? Thank you.
Rather than using Ext.util.Json.decode(), normalize the data in success() method using your own logic. For example:
success: function (response) {
console.log(response);
var myData = [];
Ext.Array.forEach(response.data, function (item) {
myData.push({
name: item.name,
email: item.email,
phone: item.phone
});
});
store.load();
}
I'm a newbie with rest and angular, so my hope answer to my question is super easy.
I'm having problem working with JSON response I get from new Neo4j post transaction/commit query.
I want to access response data for each item I have in the response. I've searched how others handle this, but have found no same cases. I think I do not parse the response at all, and can not access the specific row.
Here is my code, that just prints all the json.
JS controller
function restcall($scope, $http) {
var call = '{ "statements" : [ { "statement" : "MATCH (n:Cars) RETURN n ORDER BY n.initRank DESC LIMIT 10" } ] }';
$http({
method: 'POST',
url: 'http://myserver:7474/db/data/transaction/commit',
data: call,
})
.success(function (data, status) {
$scope.status = status;
$scope.response = data.results;
})
.error(function (data, status) {
$scope.response = data || "Request failed";
$scope.status = status;
})
};
HTML that just prints out complete response
<section ng-controller="restcall">
<h2>{{status}}</h2>
</br></br>
<h3>{{response}}</h3>
</section>
And most importantly the JSON response I get
{
"results":[{
"columns":[
"n"
],
"data":[
{"row":[{"name":"Car1","initRank":"..."}]},
{"row":[{"name":"Car2","initRank":"..."}]},
{"row":[{"name":"Car3","initRank":"..."}]},
{"row":[{"name":"Car4","initRank":"..."}]},
{"row":[{"name":"Car5","initRank":"..."}]},
{"row":[{"name":"Car6","initRank":"..."}]}]
}],
"errors":[]
}
So basically now I just print out in html my json response.
Now, how do I access individual rows to get i.e. Car3 properties??
I tried the data.results[0][0].data... and also to parse my string, but when I add next .data it just doesn't show a thing, same thing with parsing.. Can someone help please.
Based on that JSON response, you would use data.results[0].data[2].row[0].initRank to access the "initRank" of Car3. You shouldn't need to do any extra parsing of the response. It should already be an object in your callback.
I am working in DOJO and my task is i have one JSON file and the datas are coming from JSON url. So now i have to read JSON url and save the datas to browser using HTML5 localStorage, after saving i have to read datas from browser and i have to display in DOJO. Guys any one know about this kindly help me..
Function for getting json data
function accessDomain(dom_sclapi, handle) {
var apiResponse;
//accessSameDomain
if(!handle) {
handle = "json";
}
dojo.xhrGet({
url : dom_sclapi,
handleAs: handle,
sync: true,
headers: { "Accept": "application/json" },
//Success
load: function(Response) {
apiResponse = Response;
},
// Ooops! Error!
error: function(Error, ioArgs) {
//apiResponse = Error;
//console.log(ioArgs.xhr.status);
}
});
//apiResponse
return apiResponse;
}
where dom_sclapi = <json url>
Call
var data = accessDomain(<jsonurl>,'json');
then
console.log(data);
You can see the json o/p in console window. Now you can dispaly to html page using,
dojo.forEach(data, function(eachData){
//script for each json element eg: eachData.displayName;
});