Need help making this translation function work with an array input - javascript

I am trying to input an array of string values and translate them using an API then bring them back and display the array in the same order.
I have been trying to make this work using the async.map function, however I can not find any resources or examples that help me understand how to properly do this.
This is what I have so far,
var request = require('request');
var async = require('async');
var array = ["This", "wedding", "is", "horse shit"]
var translate = function translate(inText, doneCallback) {
request({
method: 'POST',
url: "https://lc-api.sdl.com/translate",
headers: {
"Content-type": 'application/json',
"Accept": 'application/json',
"Authorization": 'LC apiKey=api_key_here'
},
body: {
to: 'fra',
from: 'eng',
text: inText
},
json: true
}, doneCallback(null, body.translation)));
}
async.map(array, translate, function (err, result) {
if (err) {
console.log("error");
} else {
console.log(result);
}
});
Any help in pointing out the proper way to do this, or a better way is much appreciated.

I think the error is whithin the translate function, the callback is called instantaneously, you don't wait for the asynchronous answer. Try something like this:
funcion translate(inText, doneCallback) {
$.get({ /* params */ }, function(response) {
// Make the external callback only in the callback of the request
doneCallback(null, response.translation);
});
});

Related

Creating a reusable function for deleting/confirming using callbacks

i'm not sure if this question has been asked before, i did check but i'm not sure how to actually search for it tbh.
I want to create a reusable function for deleting, confirming based on user decision. I created this simple function to edit element data with object values but i'm not able to run the callback that was set in the first function.
Or maybe it's even possible to somehow return a bool from that function based on user's decision?
Here's the logical example of what i want to achieve
function run(options, cb){
if(options['success']){
cb();
}
}
var options = {success: true};
var cbarray = new Array('id', 'token');
//calling the function and setting the callback
run(options, function(cbarray){
$.ajax({
url: 'blabla',
type: 'post',
data: {id: cbarray[0], token: cbarray[1]},
success: function(resp){
console.log(resp);
}, error: function(resp){
console.log(resp);
}
});
});
It's kinda hard to explain so i created this jsfiddle with my own code
https://jsfiddle.net/43zrqkvm/7/
Maybe i should actually use promises for that? I haven't yet had time to learn promises but maybe i should?
when you defining callback function you'r requesting argument that will be used in function body (in you'r case in ajax options) but in Run function you do not passing it
it must look like this
function run(options,arg, cb){
if(options['success']){
cb(arg);
}
}
var options = {success: true};
var cbarray = new Array('id', 'token');
//calling the function and setting the callback
run(options,cbarray, function(arg){
$.ajax({
url: 'blabla',
type: 'post',
data: {id: arg[0], token: arg[1]},
success: function(resp){
console.log(resp);
}, error: function(resp){
console.log(resp);
}
});
});

Best approach to making sequential POST requests in Javascript

So I have an array that contains data that needs to be sent as part of the payload for POST requests that need to be made. Now, these need to be made sequentially, since I need to display the particular payload , then the result(the result being the response that is returned after making the POST request with the payload), then the next payload, then the next result and so on, on my page. I was just wondering what would be the best approach to accomplish this.So this is how I'm approaching it at the moment:
for (var i = 0; i < quotesList.length; i++) {
var response = $.ajax({
type: "POST",
url: url,
data: JSON.stringify(quotesList[i]),
success: add_to_page,
},
timeout: 300000,
error: function(){
console.log("Some Error!")
},
contentType: "application/json"
})
Obviously, the issue here that arises is there's no guarantee in terms of the getting that sequence right and also I wasn't quite sure how exactly to keep a track of the payload since trying to add it as a part of the success function only gets me the last element in the last(presumably the last request thats fired)
You can try something like below.
let quotesListIndex = 0;
function sendAjaxCall() {
if (quotesListIndex < quotesList.length) {
var response = $.ajax({
type: "POST",
url: url,
data: JSON.stringify(quotesList[quotesListIndex++]),
success: function () {
//... Add code here
sendAjaxCall(); // Call the function again for next request
},
timeout: 300000,
error: function () {
console.log("Some Error!")
},
contentType: "application/json"
})
} else {
return;
}
}
Add one global variable to track the index. and call function recursively. Once the index reached the array size then return from function.

understanding a http request and nested function in ajax

I am referencing this code to build a twitch viewer app, which I'm having difficulties in understanding:
$(document).ready(function() {
let usernames = ["user1", "user2", "user3", "user4"];
usernames.forEach(function(user) {
let http = "https://api.twitch.tv/kraken/streams/" + user;
function getAjax(getdata) {
$.ajax({
url: http,
headers: {
'Client-ID': 'myclientid'
},
success: function(data) {
getdata(data)
}
});
}
});
})
What does 'headers' do exactly? I looked it up on twitch and couldn't find a detailed description. It doesn't look like it gives/adds anything to my http request. Twitch says the header "securely identify my application." but wasn't sure what that mean. I thought if it works similar to an API key it should be included in the request.
What does the 'getdata' function in this code do? does it simply store the data i receive from the ajax request?
1) Headers are included in the request. You should be able to see them in the developer tools; this is what it looks like in Firefox
2) getdata is a callback function that is passed into getAjax by consumers, which can then act on the data as necessary, for example...
getAjax(function(data) {
// do something with data
})
Note also, you're redeclaring the function in each iteration of the loop, but not actually calling it anywhere. You probably want something more like this...
$(document).ready(function() {
let usernames = ["user1", "user2", "user3", "user4"];
function getAjax(url, getdata) {
$.ajax({
url: url,
headers: {
'Client-ID': 'myclientid'
},
success: function(data) {
getdata(data)
}
});
}
usernames.forEach(function(user) {
let http = "https://api.twitch.tv/kraken/streams/" + user;
getAjax(http, function(data) {
// do something with data
})
});
})

Correct format for post request from axios to PHP

I'm trying to use Axios (because it's light) for a post request to PHP. Here's my code for the post request:
var params = {
method: 'post',
url: 'http://myurl.com',
data: myData,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
axios(params).then(...).catch(...);
I've had mild success with the following myData:
var myData = {
data: {
lastRequest: '2017-10-19T17:09:10.943Z'
},
validationType: 'timestamp'
}
Bizarrely, though, in PHP, it turns up as the array key in $_POST:
// var_dump of $_POST
'{"data":{"lastRequest":"2017-10-19T17:09:10.943Z"},"validationType":"timestamp"}' => ''
So, although it's a bit strange, I can do something with it. However, I also want to send more complex data from a third-party API:
var myData = {
data: {
coord: {
lon: -9.99,
lat: 52.71
},
weather: [
{
id: 802,
main: 'Clouds',
description: 'scattered clouds',
icon: '03d'
}
],
// etc
},
validationType: "weather"
}
This yields a really weird $_POST array in PHP:
// var_dump of $_POST
'{"data":{"coord":{"lon":-9_99,"lat":52_71},"weather":' => [
'{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03d"}' => ''
]
Not much I can do with that. I can't see what I'm doing wrong. I know there are a few other similar StackOverflow questions, but I can't find any that have been answered satisfactorily. Would appreciate any help, thanks!
EDIT: Regarding URLSearchParams:
It seems to work OK with simple key-value pairs...
var myData = new URLSearchParams();
myData.append('lastRequest', '2017-10-19T17:09:10.943Z');
console.log(myData.toString()); // lastRequest=2017-10-19T17%3A09%3A10.943Z
...and arrays:
myData.append('myArray', ['foo', 'bar']);
console.log(myData.toString()); // myArray=foo%2Cbar (%2C is a comma)
But it doesn't handle objects, which is quite important in my case:
myData.append('myObject', {foo: 'bar'});
console.log(myData.toString()); // myObject=%5Bobject+Object%5D
After some testing with Postman and jQuery, I've reached the conclusion that it's probably an issue with Axios. Following jQuery code (which seems to me to be equivalent to the above Axios code) does exactly what I want:
$.ajax({
method: 'post',
url: 'http://myurl.com',
data: myData,
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});
I was hoping to use a more lightweight library, but it's more important that it works!
EDIT: Came across jQuery Builder, which can help to make jQuery more lightweight.

HTTPS request not posting body of REST request

I'm trying to POST to an API endpoint on my server. I know my endpoint works because if I use Advanced REST Client, I can hit it and get a JSON response as expected. The problem seems to be that no data is being sent in the body of my request despite calling request.write(postData) which contains a key, value pair. Without this data being sent in the body, my server returns a 401 error as expected without this information. Printing out the content of the POST server-side is empty but I'm clueless as to why it's empty.
var postData = querystring.stringify({
"access_token" : accessToken,
"id": applianceId
});
var serverError = function (e) {
log("Error", e.message);
context.fail(generateControlError(requestName, "DEPENDENT_SERVICE_UNAVAILABLE", "Unable to connect to server"));
};
var callback = function(response) {
var str = "";
response.on("data", function(chunk) {
str += chunk.toString("utf-8");
});
response.on("end", function() {
result = generateResult(CONTROL, requestName.replace("Request", "Confirmation"), messageId);
context.succeed(result);
});
response.on("error", serverError);
};
var options = {
hostname: REMOTE_CLOUD_HOSTNAME,
port: 443,
path: REMOTE_CLOUD_BASE_PATH + "/" + endpoint,
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
};
var request = https.request(options, callback);
request.on("error", serverError);
//This doesn't seem to write anything since if I print out the POST
//data server-side it's empty; however, if I print out the value of
//postData here, it looks as expected: 'access_token=xxxxx'
request.write(postData);
request.end();
I have testing you code again httpbin.org/post and it seems that it is working.
I believe that the issue related to, that your should POST application/json and not "application/x-www-form-urlencoded
Please try to change the header
headers: {
"Content-Type": "application/json"
}
Then, try to change the postData to JSON string:
var postData=JSON.stringify({access_token:"xxxxx"})
To be sure that problem you success to send and the problem is not local (maybe there is an issue in your server), change the target to mirror URL:
var options = {
hostname: "httpbin.org",
path:'/post',
port: 443,
method: "POST",
headers: {
"Content-Type": "application/json"
}
};
If there is no problem in your NodeJS version, the is the response you should get: (It is mean that the server got the posted data)
{
"args": {},
"data": "{\"access_token\":\"xxxxx\"}",
"files": {},
"form": {},
"headers": {
"Content-Length": "24",
"Content-Type": "application/json",
"Host": "httpbin.org"
},
"json": {
"access_token": "xxxxx"
},
"origin": "5.29.63.30",
"url": "https://httpbin.org/post"
}
BTW: I really recommend you to move to a library to manage the request for you:
https://github.com/request/request - Very popular
https://github.com/request/request-promise - For popular who like to use the Promise syntax (The next thing in JavaScript)
https://github.com/visionmedia/superagent - For people who like to write same code in Browser & Server

Categories