is there a standard established way to do the following:
curl -i "http://api.waqi.info/feed/shanghai/?token=demo"
returns
{
status: "ok",
data: {
aqi: 70,
time: {
s: "2016-12-11 12:00:00"
},
city: {
name: "Shanghai",
url: "http://aqicn.org/city/shanghai/",
geo: [
"31.2047372",
"121.4489017"
]
},
iaqi: {
pm25: "..."
}
}
}
i want to make a simple page that calls the API and formats the result. but i want to do it in the browser so that i can host a serverless webpage.
Ive look at Angular and react but it seems an awful lot of setup and baggage to do something simple like this.
i could write the jscript and html from scratch but also feels like there should be some libraries to support this.
You can write an ajax call to get the data like this:
fetch('http://api.waqi.info/feed/shanghai/?token=demo')
.then(function(response) {
return response.json();
})
.then(function(jsonData) {
console.log(jsonData); //the data you want to get
});
More information here
If you want to use some library, you can try superagent
I have used jQuery plugin and used $.ajax() method: See here.
Later, I split all data using keys as shown below;
$.ajax({
url: 'http://api.waqi.info/feed/shanghai/?token=demo',
success: function(ajax) {
console.log(ajax);
let data = ajax.data; // Object
let api = data.api; // Int
let attributions = data.attributions; // Array [3]
let cityCoords = data.city.geo; // Array [2]
let cityName = data.city.name; // String
let cityUrl = data.city.url; // String
let dominentpol = data.dominentpol; // String
let iaqi = data.iaqi; // Object Keys = [co, d, h, no2, o3, p ,pm10, pm25, so2, t, w, wd]
let idx = data.idx; // Int
let time = data.time; // Object Keys = [s, tz, v]
let status = ajax.status;
console.log("Data Object: "
+ data +
"\nAPI Version: "
+ api +
"\nAttributions #1 Name: "
+ attributions[0].name +
"\nAttributions #1 Url: "
+ attributions[0].url +
"\nAttributions #2 Name: "
+ attributions[1].name +
"\nAttributions #2 Url: "
+ attributions[1].url +
"\nAttributions #3 Name: "
+ attributions[2].name +
"\nAttributions #3 Url: "
+ attributions[2].url +
"\nCity Longitude: "
+ cityCoords[0] +
"\nCity Latitude: "
+ cityCoords[1] +
"\nCity Name: "
+ cityName +
"\nCity Url: "
+ cityUrl +
"\dDominentpol: "
+ dominentpol +
"\nIaqi Key [co]: "
+ iaqi.co +
"\nIaqi Key [d]: "
+ iaqi.d +
"\nIaqi Key [h]: "
+ iaqi.h +
"\nIaqi Key [no2]: "
+ iaqi.no2 +
"\nIaqi Key [o3]: "
+ iaqi.o3 +
"\nIaqi Key [p]: "
+ iaqi.p +
"\nIaqi Key [pm10]: "
+ iaqi.pm10 +
"\nIaqi Key [pm25]: "
+ iaqi.pm25 +
"\nIaqi Key [so2]: "
+ iaqi.so2 +
"\nIaqi Key [t]: "
+ iaqi.t +
"\nIaqi Key [w]: "
+ iaqi.w +
"\nIaqi Key [wd]: "
+ iaqi.wd +
"\nIdx: "
+ idx +
"\nTime Key = [s]: "
+ time.s +
"\nTime Key = [tz]:"
+ time.tz +
"\nTime Key = [v]:"
+ time.v +
"\nStatus: "
+ status);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Related
I have an exercise where from an object constructor, I have created several objects, all with an ID property.
The first part of the exercise consist in pairing each object, compare their markAv properties and print the one that had it bigger.
[ a vs b => b wins]
They suggested to do so by using the ID property but I didn't know how to do it that way... so I tried a workaround, as you will see in the code below.
However, the second part of the exercise wants me to do the same but, this time, creating the pairs randomly. Here I have tried to use the ID property by generating a random number that matches the ID but I don´t know how to structure the code for it to work.
The output for the second part should be the same as above, with the only difference that the pairing is now randomly generated.
I have added a partial solution for the second part, partial because from time to time it throws an error that I can´t identify. However, I think I'm getting close to get my desired output.
I would really appreciate if anyone could give me a hint for me to crack the code below and to get it working because I really want to understand how to do this.
class Avenger {
constructor(name, classRoom, city, job, studies, markAv, id) {
this.name = name;
this.classRoom = classRoom;
this.city = city;
this.job = job;
this.studies = studies;
this.markAv = markAv;
this.id = id;
}
heroList() {
return this.name + " " + this.classRoom + " " + this.city + " " + this.job + " " + this.studies + " " + this.markAv + " " + this.id
}
}
const tonyStark = new Avenger("Tony Stark", "XI", "NYC", "Ingeneer", "MIT", 10, 1)
const hulk = new Avenger("Hulk", "X", "Toledo", "Destroyer", "Scientific", 7, 2)
const daredevil = new Avenger("Daredevil", "IX", "NYC", "Lawyer", "Fighter", 2, 3)
const magneto = new Avenger("Magneto", "XXI", "SBD", "Unemployed", "Driver", 5, 4)
const unknown = new Avenger("Unknown", "L", "CDY", "President", "Clerck", 17, 5)
const xavi = new Avenger("Xavi", "XX", "BCN", "Analist", "Calle", 7, 6)
let heroes = [daredevil, hulk, tonyStark, magneto, unknown, xavi]
function getPairs(array) {
function getPairs(array) {
for (let i = 0; i < array.length; i += 2) {
if (array[i].markAv < array[i + 1].markAv) {
console.log(array[i].name + " vs " + array[i + 1].name + " " + array[i + 1].name + " Wins")
} else if (array[i].markAv > array[i + 1].markAv) {
console.log(array[i].name + " vs " + array[i + 1].name + " " + array[i].name + " Wins")
}
}
}
getPairs(heroes)
///
function randomAv(array) {
let result = []
let hero1 = heroes[Math.floor(Math.random() * 6) + 1]
for(let i = 0; i<array.length; i++){
if (array[i].markAv <= hero1.markAv && array[i].id != hero1.id) {
result.push(console.log(array[i].name + " vs " + hero1.name + " " + array[i].name + " Wins"))
} else if(array[i].markAv >= hero1.markAv && array[i].id != hero1.id) {
result.push(console.log(array[i].name + " vs " + hero1.name + " " + hero1.name + " Wins"))
}
}
console.log(result)
}
First shuffle the array:
let heroes = [daredevil, hulk, tonyStark, magneto, unknown, xavi]
let heroes_shuffle = heroes.sort((a, b) => 0.5 - Math.random())
Then do as normal
getPairs(heroes_shuffle )
All Possible Combination :
function allPairs(heroes) {
while (heroes) {
[hero, ...heroes] = heroes
for (enemy of heroes) {
if (hero.markAv === enemy.markAv)
console.log(hero.name + " vs " + enemy.name + ": draw")
else if (hero.markAv < enemy.markAv)
console.log(hero.name + " vs " + enemy.name + ": " + enemy.name + " Wins")
else
console.log(hero.name + " vs " + enemy.name + ": " + hero.name + " Wins")
}
}
}
You can take the function from here https://stackoverflow.com/a/7228322/1117736
And do something like this:
class Avenger {
constructor(name, classRoom, city, job, studies, markAv, id) {
this.name = name;
this.classRoom = classRoom;
this.city = city;
this.job = job;
this.studies = studies;
this.markAv = markAv;
this.id = id;
}
heroList() {
return this.name + " " + this.classRoom + " " + this.city + " " + this.job + " " + this.studies + " " + this.markAv + " " + this.id
}
}
const tonyStark = new Avenger("Tony Stark", "XI", "NYC", "Ingeneer", "MIT", 10, 1)
const hulk = new Avenger("Hulk", "X", "Toledo", "Destroyer", "Scientific", 7, 2)
const daredevil = new Avenger("Daredevil", "IX", "NYC", "Lawyer", "Fighter", 2, 3)
const magneto = new Avenger("Magneto", "XXI", "SBD", "Unemployed", "Driver", 5, 4)
const unknown = new Avenger("Unknown", "L", "CDY", "President", "Clerck", 17, 5)
const xavi = new Avenger("Xavi", "XX", "BCN", "Analist", "Calle", 7, 6)
let heroes = [daredevil, hulk, tonyStark, magneto, unknown, xavi]
function randomIntFromInterval(min, max) { // min and max included
return Math.floor(Math.random() * (max - min + 1) + min)
}
let hero1 = heroes[randomIntFromInterval(1, 6)]
let hero2 = heroes[randomIntFromInterval(1, 6)]
if (hero1.markAv < hero2.markAv) {
console.log(hero1.name + " vs " + hero2.name + " " + hero1.name + " Wins")
} else if(hero1.markAv > hero2.markAv) {
console.log(hero1.name + " vs " + hero2.name + " " + hero2.name + " Wins")
}
I am making a POST request with Axios within a for loop to create leads in mass. The leads get created but the issue that I'm noticing is that even though I get a 200 response, in the network tab under timing, the requests are actually never finished, they just say "stalled".
Below is a screenshot of what I'm talking about
This can become a problem, because if I do other POST requests like this, not all the requests will go through. I think I read somewhere that Google Chrome only allows up to 6 connections open or something like that. If these requests are stalling, I can only assume that those connections are staying open, and that's what's causing this to happen.
So I guess my question is, what's the best way to put this POST request in a for loop without the requests stalling? Should I make it asynchronous, and if so how would I do that with my code?
Here is my server.js
app.get('/create*', (request, response) => {
var baseurl = 'https://OURACC.nocrm.io/api/v2/'
var apikey = 'APIKEY'
var title = "";
var description = "";
var tags = [];
var pathname = request.url; // retrieves the requested pathname (ie, /crm/path)
pathname = pathname.split('?');
pathname = pathname[0].split('/')
var parameters = request.query.params;
var path = pathname[2]; // gets request path for the crm
title = parameters.title
description = parameters.description
tags = parameters.tags
var params = {
title: title,
description: description,
tags: tags
}
if(path === 'leads'){
// console.log("Inside Lead Creation");
axios.post(baseurl + path,
params
,{
headers: {'X-API-KEY': apikey, content_type: "json", accept: "application/json"}
}).then(function(res){
console.log("Lead Created");
}).catch(function(error){
console.log("Error: " + error);
})
}
})
This is where I call it client side
CreateLeads(){
var prospects = this.state.Prospects;
var description = "";
var title = "";
var tags = [];
for(var i = 0; i < prospects.length; i++){
tags = prospects[i].tags;
title = prospects[i].leadName;
description = "Business Name: " + prospects[i].businessName + "\n" +
"Customer Number: " + prospects[i].custNumber + "\n" +
"Corporate Name: " + prospects[i].corpName + "\n" +
"Corporate Contact Name: " + prospects[i].corpContName + "\n" +
"Corporate Phone: " + prospects[i].corpPhone + "\n" +
"Corporate Email: " + prospects[i].corpEmail + "\n" +
"Customer First Name: " + prospects[i].custFirst + "\n" +
"Customer Last Name: " + prospects[i].custLast + "\n" +
"Street: " + prospects[i].street + "\n" +
"City: " + prospects[i].city + "\n" +
"State: " + prospects[i].state + "\n" +
"Zip: " + prospects[i].zip + "\n" +
"Phone 1: " + prospects[i].phone + "\n" +
"Category: " + prospects[i].category;
var data = {
title: title,
description: description,
tags: tags,
}
console.log(data);
$.get('/create/leads', {params: data}).then(response => {
console.log(response);
}).catch(error => {
console.log("Error: " + error);
})
}
}
I am manipulating string to display in UI, Data is being dynamically with below code sometime i don't get header and details so how to make IHeader and IResponse optional for the string concatenation below.
if i dont have IHeader it will break at IHeader.id and throw exception i want to display whatever data is available to render.
main.js
const data = [{
id: "header",
name: "IHeader"
}, {
id: "param",
name: "IParams"
}, {
id: "details",
name: "IResponse"
}]
function buildText(data) {
var IParams;
var IResponse;
var IHeader;
for (var item of data) {
if (item.id === "param") {
IParams = item;
} else if (item.id === "header") {
IHeader = item;
} else if (item.id === "details") {
IResponse = item;
}
}
var text = '';
text += app + '.setConfig({\n' + "env:" + getEnv() + '\n});' + '\n\n';
text += 'let param:' + IParams.name + ' ' + '=' + '' + JSON.stringify(request, null, 4) + ';\n\n';
text += ref + '(' + 'param,(result:' + ' ' + '{' + '\n' + IHeader.id + ':' + IHeader.name + '\n' + IResponse.id + ':' + IResponse.name + '\n' + '})' + ' ' +
' => {\n console.log(result); \n});';
}
1 - You can try to create an object with empty values. That'll prevent the exception.
emptyObject = {id: ""} // more empty keys, if there is
IParam = (item.id === "param") ? item : emptyObject
2 - Or ignore that concatenation of the variable if undefined or null.
if (Iparam) {
// concatenation ..
}
How do I concatenate these strings to get value from a variable. I want to avoid eval as so many of you are not keen on its use.
function getLesson() {
var lesson = "lesson" + localStorage.lessonNGS;
document.getElementById("lessonNumber").innerHTML = "Lesson " + (eval(lesson + "." + number));
document.getElementById("lessonTitle").innerHTML = (eval(lesson + "." + title));
document.getElementById("lessonScore").src = (eval(lesson + "." + score));
document.getElementById("mp3").src = (eval(lesson + "." + trackmp3));
document.getElementById("ogg").src = (eval(lesson + "." + trackogg));
document.getElementById("lessonTrack").load();
}
This works but I'm told it will cause me conflicts in some browsers.
Simply remove the eval
// Demo data
localStorage.setItem("lessonNGS",1);
var lesson1 = {
number: "1",
title: "Quarter Notes",
score: "scores/01_quarternotes.jpg",
trackmp3: "tracks/mp3/01_quarternotekeyexercises.mp3",
trackogg: "tracks/ogg/01_quarternotekeyexercises.ogg"
};
function getLesson() {
debugger;
var lesson = window["lesson" + localStorage.lessonNGS];
document.getElementById("lessonNumber").innerHTML = "Lesson " + lesson.number;
document.getElementById("lessonTitle").innerHTML = lesson.title;
document.getElementById("lessonScore").src = lesson.score;
document.getElementById("mp3").src = lesson.trackmp3;
document.getElementById("ogg").src = lesson.trackogg;
document.getElementById("lessonTrack").load();
}
Javascript String.prototype.concat():
str.concat(string2, string3[, ..., stringN])
Example:
var hello = 'Hello, ';
console.log(hello.concat('Kevin', ' have a nice day.'));
I want to get the value of "status" from data in the code below,
$.ajax({
dataType: "json",
url: "calendar/php/date.php",
type: "POST",
data: {
select: "%Y-%c-%e",
where: "%Y-%c",
d: y + "-" + m,
order: "timestamp, id"
},
beforeSend: function() { $('#loading').show(); },
success: function(data) {
sessionStorage[y+"-"+m] = JSON.stringify(data);
for (var key in data) {
$("<span class=\"label label-success\">" + Object.keys(data[key]).length + "</span>").prependTo($("#" + key));
console.log('key: ' + key + '\n' + 'value: ' + JSON.stringify(data));
}
},
complete: function() { $('#loading').fadeOut(200); }
});
Following is some part of the console.log result:
key: 2014-11-11
value: {"2014-11-11":[{"0":"3","1":"2014-11-11 11:11:00","2":"2014-11-28 10:12:00","3":"test","4":"test","5":"0","6":"","7":"","8":"","9":"0","10":"0","11":"0","12":"0","13":"0","14":"0","15":"0","16":"","17":"2014-11-11","id":"3","timestamp":"2014-11-11 11:11:00","toTimestamp":"2014-11-28 10:12:00","title":"test","location":"test","status":"0","organizer":"","organizerContact":"","organizerEmail":"","projector":"0","laptop":"0","speaker":"0","pointer":"0","whiteboard":"0","mediaCoverage":"0","parking":"0","remark":"","selector":"2014-11-11"}],"2014-11-12":[{"0":"15","1":"2014-11-12 07:07:00","2":"2014-11-12 03:09:00","3":"test","4":"test","5":"1","6":"","7":"","8":"","9":"0","10":"0","11":"0","12":"0","13":"0","14":"0","15":"0","16":"","17":"2014-11-12","id":"15","timestamp":"2014-11-12 07:07:00","toTimestamp":"2014-11-12 03:09:00","title":"test","location":"test","status":"1","organizer":"","organizerContact":"","organizerEmail":"","projector":"0","laptop":"0","speaker":"0","pointer":"0","whiteboard":"0","mediaCoverage":"0","parking":"0","remark":"","selector":"2014-11-12"}]}
I want get the value of "status" i.e 0, as seen in the above result, in order to include it in the for loop (for (var key in data) {...}) to change the class 'label-success' to 'label-failure' if the status is 0. Could you help me?
Hello maybe I am wrong but
console.log('key: ' + key + '\n' + 'value: ' + JSON.stringify(data));
returns the whole data object in string format when you say JSON.stringify(data);
You want the value which is returned when you give data a specific key to read values from:
console.log('key: ' + key + '\n' + 'value: ' + data[key]);
EDIT: Im not sure if data[key] will return a [object Object]... if it does try JSON.stringify(data[key])
I would also suggest Itterating through data with the
for(var i = 0; i < data.length; i++){}
this makes it readable and is measured the most performant way of extracting data.
EDIT nr 2:
This is your object:
{"2014-11-11":[{"0":"3","1":"2014-11-11 11:11:00","2":"2014-11-28 10:12:00","3":"test","4":"test","5":"0","6":"","7":"","8":"","9":"0","10":"0","11":"0","12":"0","13":"0","14":"0","15":"0","16":"","17":"2014-11-11","id":"3","timestamp":"2014-11-11 11:11:00","toTimestamp":"2014-11-28 10:12:00","title":"test","location":"test","status":"0","organizer":"","organizerContact":"","organizerEmail":"","projector":"0","laptop":"0","speaker":"0","pointer":"0","whiteboard":"0","mediaCoverage":"0","parking":"0","remark":"","selector":"2014-11-11"}],"2014-11-12":[{"0":"15","1":"2014-11-12 07:07:00","2":"2014-11-12 03:09:00","3":"test","4":"test","5":"1","6":"","7":"","8":"","9":"0","10":"0","11":"0","12":"0","13":"0","14":"0","15":"0","16":"","17":"2014-11-12","id":"15","timestamp":"2014-11-12 07:07:00","toTimestamp":"2014-11-12 03:09:00","title":"test","location":"test","status":"1","organizer":"","organizerContact":"","organizerEmail":"","projector":"0","laptop":"0","speaker":"0","pointer":"0","whiteboard":"0","mediaCoverage":"0","parking":"0","remark":"","selector":"2014-11-12"}]}
this is a bit nested, so try to get an overview of what you have:
data = {
"2014-11-11": [],
"2014-11-12": []... }
This object has a length method that returns the length of your object. this allows you to itterate over the Data Object will give you "2014-11-11" as key and with this key you can access your values like this: data[key] this will return your array...to read data from your array you will have to itterate again data[key][i]... now you can read the data inside each array element like this
data[key][i]["status"];
Hope this helped somehow... cant be bothered to write all this code :D
success: function(data) {
sessionStorage[y+"-"+m] = JSON.stringify(data);
for (var key in data) {
var status = data['status'];
var klass = status === 0 ? 'label-failure' : 'label-success';
$('<span class="label '+klass+'">' + Object.keys(data[key]).length + "</span>").prependTo($("#" + key));
console.log('key: ' + key + '\n' + 'value: ' + JSON.stringify(data));
}
},
Try this code instead.
$.ajax({
dataType: "json",
url: "calendar/php/date.php",
type: "POST",
data: {
select: "%Y-%c-%e",
where: "%Y-%c",
d: y + "-" + m,
order: "timestamp, id"
},
beforeSend: function() { $('#loading').show(); },
success: function(data) {
sessionStorage[y+"-"+m] = JSON.stringify(data);
for (var key in data) {
for (var i in data[key]) {
$("<span class=\"label " + ((data[key][i] === "0") ? "label-failure" : "label-success") + "\">" + Object.keys(data[key]).length + "</span>").prependTo($("#" + key));
}
console.log('key: ' + key + '\n' + 'value: ' + JSON.stringify(data));
}
},
complete: function() { $('#loading').fadeOut(200); }
});