I'm a bit clueless with javascript, so would appreciate pointers with what's (not) happening here.
The following snippet is supposed to populate the data variable with the response (JSON) from a PHP backend. The response variable indeed contains the data (I confirmed with Firebug and a breakpoint):
[Object { identifier=0, value="clothing made in the us"}, Object { identifier=1, value="club penguin trading cards"}, Object { identifier=2, value="cobra quad bikes"}, 22 more...]
However, by the time the return data; line is reached, data contains nothing.
var data = [];
new response.each(function(identifier, item){
this.include({value: identifier, text: item.text});
}, data);
return data;
I'm having difficulty mapping my knowledge of (eg) Perl's foreach loop with what's happening here. I'd appreciate any pointers.
Thanks
Solved
var data = [];
response.each(function(obj) {
this.include({identifier: obj.id, value: obj.descr});
}, data);
return data;
I'll eventually get this JS.
Related
**im a bit confused on how to declare an array in a deluge script. I have seen the references online but somehow i may not be using this syntax right:
x = List();
**
and here is my foreach loop
request_body is receiving the JSON array from my server
I get an error Argument type mismatches for the integration function 'zoho.crm.createrecord' at index 2 Line Number: 15
this my code to send the JSON array to CRM
async function sendToCRM(pets) {
var jsonPets = JSON.stringify(pets)
superagent
.post(insertPet_URL)
.set("Content-Type", "application/json")
.send(jsonPets)
.end((e, r) => {
console.log(r.body)
})// sends a JSON post body
}
app.post("/pets", (req,res)=> {
var pets = req.body
var petsData = []
pets.forEach(function(pet){
var tmp = {}
tmp["Name"] = pet.Ngalan
tmp["Pet_Owner"] = pet.Tagiya
tmp["Contact_Number"] = pet.Numero
tmp["Birthdate"] = pet.Kaadlawan
tmp["Breed"] = pet.Rasa
petsData.push(tmp)
})
console.log(petsData)
sendToCRM(petsData)
res.send(req.body)
res.status(200)
})
there has been no problem on the server side and im able to receive this JSON array from Postman which is the one im going to send to CRM deluge. Here is my JSON array:
[{"Ngalan":"Hachi","Tagiya":"Rex","Numero":"09778135353","Kaadlawan":"2020-12-12","Rasa":"Akita Inu"},{"Ngalan":"qwe","Tagiya":"Rex","Numero":"09778135353","Kaadlawan":"2020-12-12","Rasa":"Akita Inu"}]
Any help would be much appreciated. Thanks!
Make the request_body.tojsonlist(). then it work
First extract the keys from your response object, then iterate through your list and get the values
keys = request_body.keys();
for each key in keys
{
value = request_body.get(key)
}
I am trying to consume a .net core 2.2 web api i created and display the json data, keys AND VALUES, in a Google App Maker App. My js is very very weak (caz ive been trying to re-purpose the main example in googles docs for 7 days now with no real progress).
I have fought though many many issues to get to a final ERROR ( i hope).
When i commit some of the REST API data to the datastore. its ask for:
an array ( in js i guess arrays are objects...who knew)
a Key ( no idea how to make a key with out returning one FULL ITEM from the js object array i created for my data)
and for some form of mapping for the object ( i think i have overcome this requirement..not sure. this most likely will comeback after i fix the error bellow)
ERROR:
The function queryRecords must return an array of records, but the
array contained an element that was not a record. Error: The
function queryRecords must return an array of records, but the
array contained an element that was not a record.
Sun Sep 22 15:42:46 GMT-700 2019
Executing query for datasource Weather: (Error) : The function
queryRecords must return an array of records, but the array
contained an element that was not a record.
at loadWeatherDataSource (CallWeatherService:6:27)
at Weather.LocationTextBox.onValueChange:1:1
at Weather.LocationTextBox.onAttach:1:14
Sun Sep 22 15:42:46 GMT-700 2019
Executing query for datasource Weather failed.
Server side code
function clearEmailForm(){
var url= 'https://xxx.azurewebsites.net/api/xxxxxx/3';
var response1 = UrlFetchApp.fetch(url);
var api1= response1;
return JSON.parse(api1);
}
function cal() {
var coordinates = clearEmailForm();
return {
forecast: coordinates.Scene,
citystate: coordinates.imageurl
};
}
function calculateWeatherModel_() {
var response;
try {
response = cal();
} catch (error) {
throw new Error('Error Unable to locate provided city: \"' + response + '\".');
}
if (response === null) {
throw new Error('null Unable to locate provided city: \"' + response + '\".');
}
var forecastPeriods = response.forecast;
var citystate = response.citystate;
var arr = [];
var record = app.models.Weather.newRecord();
arr.push(record.forcast = forecastPeriods );
var record = app.models.Weather.newRecord();
arr.push(record.citystate = citystate);
return arr;
}
Client side code
function loadWeatherDataSource() {
app.datasources.Weather.load({
failure: function (error) {
displayTimedSnackBar(error.toString());
}
});
}
Client side code
return calculateWeatherModel_();
Thanks ahead of time for any and all detailed help here..I am at a complete loss and will have to delay a critical project.
I will now study and start to mastering JS as i see a clear need! I have my books and online course ready to go. if i can get some detailed help on this issue it will give my project some new life now instead of a long time from now. thank you all!
I beleive that your problem is here:
var arr = [];
var record = app.models.Weather.newRecord();
arr.push(record.forcast = forecastPeriods );
var record = app.models.Weather.newRecord();
arr.push(record.citystate = citystate);
return arr;
That is a wrong way of doing it. It should be like this:
var arr = [];
var record = app.models.Weather.newRecord();
record.forcast = forecastPeriods;
record.citystate = citystate;
arr.push(record);
return arr;
Obviously, in order for that to work, your calculated model should have a forcast field and a citystate field.
Reference: https://developers.google.com/appmaker/models/calculated#query_script_example
I did have this code working a few years ago and have recently come back to it, i have a javascript refreshing data on a web page. Im calling the server using json and receiving back what i think is ok.
My python database code, which seems to work fine.
cur = db.execute('select sensor_name, temp from cur_temps ORDER BY sensor_name')
return jsonify(cur.fetchall())
Received Json
[["BoilerRoom",24.94],["Cylinder1",49.94],["Cylinder2",42.38],["Cylinder3",41.88],["Sensor1",85],["SolidFuelFlow",59],["SolidFuelReturn",41.62]]
Im trying to get the number thats associated with Cylinder2 = 42.38
My js code that worked previously is as follows
<script type=text/javascript>
function get_temps() {
$.getJSON("_status",
function (data) {
$('#CylTop').text(data.Cylinder1 + "°")
$('#CylMid').text(data.Cylinder2 + "°")
$('#CylBot').text(data.Cylinder3 + "°")
$('#Solid_flow').text(data.SolidFuelFlow)
$('#Solid_return').text(data.SolidFuelReturn)
$('#BRoom').text(data.BoilerRoom);
console.log(data)
console.log(data.Cylinder1)
}
);
}
setInterval('get_temps()', 5000);
</script>
The console shows the (data) fine in the browser, its when i try and show anything else. ' console.log(data.Cylinder1) ' that shows undefined.
Im a newbie so im assuming some indexing needs to happen as its a array but im a bit lost.
Any guidance will be greatly appreciated.
Many Thanks
C Dabbs
You seem to be accessing the properties in the data as an object. As per the response, it is an array inside an array. So you will have to flatten it before accessing it the way you have it.
function get_temps() {
$.getJSON("_status",
function(data) {
let flattendData = data.reduce(function(acc, item) {
return Object.assign({}, acc, {
[item[0]]: item[1]
});
}, {});
$('#CylTop').text(flattendData.Cylinder1 + "°")
$('#CylMid').text(flattendData.Cylinder2 + "°")
$('#CylBot').text(flattendData.Cylinder3 + "°")
$('#Solid_flow').text(flattendData.SolidFuelFlow)
$('#Solid_return').text(flattendData.SolidFuelReturn)
$('#BRoom').text(flattendData.BoilerRoom);
console.log(flattendData)
console.log(flattendData.Cylinder1)
}
);
}
I am trying out some angularjs stuff. So I have a few arrays. One of them is artists. this is it's basic structure from console.log(artists);
artists
problem is that I can't access the elements of the array individually. I read up a lot of things regarding associative arrays and may questions on SO but none really helped. So either it is a very silly mistake I am making or it is some thing else.
Here are few results that I got with every array I have.
console.log(artists[0]); //returns undefined
console.log(artists['0']); //returns undefined
console.log(artists.length); // returns 0 in spite of the fact it showed 20 previously
console.log(Array.isArray(artists)); //returns true
And yes I created the array like this in a service, ChartService
var artists = [];
var artistids = [];
var tracks = [];
$http.get('https://api.spotify.com/v1/search/?q=genre:pop&type=artist').success(function (data) {
var items = data.artists.items;
items.forEach(function(item){
artists.push(item.name);
artistids.push(item.id);
var query = trackApi+item.id+'/top-tracks?country=SE'
$http.get(query).success(function (response) {
tracks.push({'preview': response.tracks[0].preview_url});
});
});
});
return {
Artists : artists,
Tracks : tracks
}
And my controller
console.log(ChartService.Artists); //runs fine
console.log(ChartService.Tracks); //runs fine
$scope.tracks = ChartService.Tracks;
console.log($scope.tracks); //runs fine
console.log($scope.tracks[0]); //returns undefined
console.log($scope.tracks['0']); //returns undefined
console.log($scope.tracks.length); // returns 0 in spite of the fact it showed 20 previously
console.log(Array.isArray($scope.tracks)); //returns true
The issue is that you check the content of artists before the issued http get requests have triggered their responses.
One way to resolve that is to put your code in the success callback, like this:
$http.get('https://api.spotify.com/v1/search/?q=genre:pop&type=artist').success(function (data) {
var items = data.artists.items;
items.forEach(function(item){
artists.push(item.name);
artistids.push(item.id);
var query = trackApi+item.id+'/top-tracks?country=SE'
$http.get(query).success(function (response) {
tracks.push({'preview': response.tracks[0].preview_url});
});
});
// here
console.log(artists);
});
Still, that solves it for artists, but then you'd need to do something similar if you need the tracks: as you have more then one request providing for that, you'd need to check the length of the tracks array and only if it has the complete length, like this:
$http.get('https://api.spotify.com/v1/search/?q=genre:pop&type=artist').success(function (data) {
var items = data.artists.items;
items.forEach(function(item){
artists.push(item.name);
artistids.push(item.id);
var query = trackApi+item.id+'/top-tracks?country=SE'
$http.get(query).success(function (response) {
tracks.push({'preview': response.tracks[0].preview_url});
if (tracks.length == items.length) { // all done
console.log(artists, tracks);
}
});
});
});
In a follow-up question (in comments) you explained you need this in your controller. You might look into $watch or variants of that method. If you need assistance with that, I would suggest to ask a new question.
Ok, so I am a bit of a noob with javascript and I need to read data from a csv to make a barchart with d3. The barchart is no problem for me, the reading from the csv file is. This is my code:
var dataset;
d3.csv("gender_ratio.csv", function(data) {
dataset = data;
return dataset;
});
var add = function(year, total, males, females){
var year = {
year: year,
total: total,
males: males,
females: females
};
newdata.push(year);
return newdata;
};
for (var i = 0; i < dataset.length; i += 4){
add(dataset[i], dataset[i+1], dataset[i+2], dataset[i+3]);
return newdata;
};
Can someone tell me what I is going wrong here? I am running this with modzilla firefox, so the browser security isn't the problem here.
The call to load the csv data completes asynchronously. That means your for loop is run before the data has been loaded.
If you move the for loop into the callback function of the call to d3.csv then the data will be available.
You should also check what the returned data looks like for d3.csv. Your code assumes it is returning a flat array, whereas it actually returns an array of objects where each element represents a row. If you add a console.log in the callback of the function you'll get a better sense of what the data looks like.
You also have a return statement in that for loop which means it'll only process the first element of data before exiting the loop.
d3.csv("gender_ratio.csv", function(data) {
dataset = data;
// process data here
console.log(data);
});
First, d3's .csv function works asynchronous, thus you need to call te actual bar chart drawing function within the .csv function. If the csv file has a first row featuring column names, you can use a callback function:
var dataset = [];
d3.csv("gender_ratio.csv", function(d) {
return {
year: d.year,
total: d.total,
males: d.males,
females: d.females,
};
}, function(error, rows) {
dataset = rows;
drawBarChart(); /* <<-- This would be the call to the drawing function. */
});