How to populate array with results from a series of async requests - javascript

So I'm trying to get the names and scores that are in 2 arrays player_name and player_mmr. Calling both with player_name[i] and player_mmr[i] in the fillplayer function just returns undefined. I feel like I'm missing something obvious here but for the life of me can't figure it out. I'm guessing it has to do with the use of push.
var btnmatch = document.querySelector('#get-data');
var btnchat = document.querySelector('#get-chat');
var matchid = document.querySelector('#match-id');
var tableheaders = [
'Hero',
'level',
'Name',
'Kills',
'Deaths',
'assists',
'GPM',
'XPM',
'HD',
'TD'
];
var dataheaders = [
"hero_id",
'level',
'personaname',
'kills',
'deaths',
'assists',
'gold_per_min',
'xp_per_min',
'hero_damage',
'tower_damage'
];
var playerids = [
'player1',
'player2',
'player3',
'player4',
'player5',
'player6',
'player7',
'player8',
'player9',
'player10'
];
var playeraccounts = [];
var requests = [];
var playersdata = [];
var player_name = [];
var player_mmr = [];
btnmatch.addEventListener('click', function () {
GetMatchData(matchid.value);
});
btnchat.addEventListener('click', function () {
for (i in playeraccounts) {
requests[i] = new GetPlayerData(playeraccounts[i]);
}
console.log(player_name);
console.log(typeof player_name);
console.log(player_mmr);
fillplayer();
});
function GetPlayerData(accountid) {
var Url = 'https://api.opendota.com/api/players/' + accountid;
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", Url, true);
xmlHttp.onreadystatechange = function ProcessRequestPlayer() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
if (xmlHttp.responseText == "Not found") {
console.log("not found");
} else {
var info = xmlHttp.responseText;
var playerjson = JSON.parse(info);
player_name.push(playerjson.profile.personaname);
if (playerjson.solo_competitive_rank === null) {
player_mmr.push(playerjson.mmr_estimate.estimate);
} else {
player_mmr.push(playerjson.solo_competitive_rank);
}
}
}
};
xmlHttp.send();
}
function GetMatchData(id) {
var Url = 'https://api.opendota.com/api/matches/' + id;
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", Url, true);
xmlHttp.onreadystatechange = function ProcessRequestMatch() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
if (xmlHttp.responseText == "Not found") {
console.log("not found")
} else {
var info = xmlHttp.responseText;
var testjson = JSON.parse(info);
createTable2(testjson);
getaccountids(testjson);
}
}
};
xmlHttp.send();
}
function getaccountids(json) {
Object.keys(json.players).forEach(function (i) {
playeraccounts.push(json.players[i].account_id);
});
}
function fillplayer() {
console.log(player_name);
console.log(player_mmr);
for (var i = 0; i < playerids.length; i++) {
console.log(player_name[i]);
document.getElementById(playerids[i]).getElementsByClassName('name')[0].innerHTML = player_name + ': ';
document.getElementById(playerids[i]).getElementsByClassName('mmr')[0].innerHTML = player_mmr[i];
}
}
function createTable2(json) {
// Create table.
var table = "<table class='game-table'>";
table += "<thead>";
table += "<tr>";
for (var i = 0; i < 10; i++) {
table += "<th>" + tableheaders[i] + "</th>";
}
table += "</tr>";
table += "</thead>";
table += "<tbody>";
for (var i = 0; i < 5; i++) {
table += "<tr class='radiant'>";
for (var x = 0; x < dataheaders.length; x++) {
table += "<td>" + json.players[i][dataheaders[x]] + "</td>";
}
table += "</tr>";
}
for (var i = 5; i < 10; i++) {
table += "<tr class='dire'>";
for (var x = 0; x < dataheaders.length; x++) {
table += "<td>" + json.players[i][dataheaders[x]] + "</td>";
}
table += "</tr>";
}
table += "</tbody>";
table += "</table>";
var sectie = document.getElementById('table');
if (json.radiant_win == false) {
var winnertekst = document.createTextNode('Dire Victory');
} else {
var winnertekst = document.createTextNode('Radiant Victory');
}
console.log(table);
console.log(typeof table);
console.log(sectie);
document.getElementsByClassName('winnersect')[0].appendChild(winnertekst);
sectie.innerHTML = table;
}

As marekful said you could use promises or you could take a look to Async Functions
and if you're not targeting IE as a browser, you could use the
Fetch API
instead of XMLHttpRequest and have a cleaner structure. Both of these two return a promise that you can consume.
One more source that's showing how you can combine fetch and async functions
JavaScript Fetch API and using Async/Await .

Related

How to open and makes query to sqlite database with JavaScript

I'm trying to do a client-side database visualizer with JS. I have never used JavaScript for doing this type of stuff, so I searched online and I found out this web page. This is the script that I have done.
<html>
<head>
<script>
function handleFiles(files)
{
var file = files[0];
var reader = new FileReader();
reader.readAsBinaryString(file);
openSqliteDb(reader);
}
function openSqliteDb(reader)
{
setTimeout(function () {
if(reader.readyState == reader.DONE)
{
var database = SQL.open(bin2Array(reader.result));
document.write("2");
executeQuery("SELECT * FROM User", database);
}
else
{
openSqliteDb(reader);
}
}, 500);
}
function executeQuery(commands, database)
{
document.write("1");
commands = commands.replace(/n/g, '; ');
try {
var data = database.exec(commands);
document.write(data);
processData(data);
} catch(e) {
console.log(e);
}
}
function processData(data)
{
document.write("1");
var colHeaders = [];
var colMap = {};
var tableContent = [];
var tableHtml = [];
tableHtml.push("<table border='1' cellspacing='2' cellpadding-'3'>");
for (var i = 0; i < data.length; i++) {
tableContent.push("<tr>");
var dataElem = data[i];
if (dataElem instanceof Array) {
for (var j = 0; j < dataElem.length; j++) {
var element = dataElem[j];
if (element.column && !colMap[element.column]) {
colHeaders.push("<th>" + element.column + "</th>");
colMap[element.column] = colHeaders.length;
tableContent.push("<td> " + element.value + "</td>");
} else {
tableContent.push("<td> " + element.value + "</td>");
}
}
} else {
if (element.column && !colMap[element.column]) {
colHeaders.push(element.column);
colMap[element.column] = colHeaders.length;
}
}
tableContent.push("</tr>");
}
tableHtml.push(colHeaders.join(" "));
tableHtml.push(tableContent.join(" "));
tableHtml.push("</table>");
document.getElementById("table").innerHTML = tableHtml.join(" ");
}
</script>
</head>
<body>
<input type="file" id="input" onchange="handleFiles(this.files)">
</body>
</html>
I can't figure it out why it is not working, but I think that the problem is the line var database = SQL.open(bin2Array(reader.result)); in the openSqliteDb() function. Can somebody help me?

How to iterate through a javascript object?

I am making a server side API call. The user can input ingredients and search. When the data is submitted, I see on my terminal this as my API call:
"http://www.recipepuppy.com/api/?i=[object Object]".
I am hoping for it to look like this:
"http://www.recipepuppy.com/api/?i=milk,flour,sugar,egg"
Here is my code:
router.get("/whatCanIMake", function(request, response){
var inputIngredients = request.query;
var ingredientString = "";
console.log(inputIngredients);
for (var i = 0; i<inputIngredients.length; i++){
ingredientString += inputIngredients[i] + ",";
}
var api = "http://www.recipepuppy.com/api/?i=" + inputIngredients + "";
console.log(api);
console.log("inputingredients", inputIngredients);
request.get(api, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
});
});
I would use Lodash _.forEach method:
https://lodash.com/docs#forEach
var ingredientString = "";
_.forEach(inputIngredients, function(value,key){
if(ingredientString.length != ""){
ingredientString += "," + value;
}
else {
ingredientString = value;
}
});
router.get("/whatCanIMake", function(request, response){
var inputIngredients = request.query;
var ingredientString = "";
console.log(inputIngredients);
//for (var i = 0; i<inputIngredients.length; i++){
// ingredientString += inputIngredients[i] + ",";
//}
for (var property in inputIngredients)
{
if (inputIngredients.hasOwnProperty(property)) {
ingredientString += property + ",";
}
}
//rest of your code here

im trying to add a json object response array of dates to an array in javascript and use this array in order to enable days in a jquery calendar

Note that if i directly put my dates into the array enabledDates, it will work.
var enabledDays = [];
var answ = '';
function choosedoc(){
var xmlhttp = getXMLHttpRequest();
var actionmode = 1;
var doctorid = document.getElementById('doctorid').value;
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var data = $.parseJSON(xmlhttp.responseText);
var msg = data[0].message;
if (msg != "") {
alert(decodeURIComponent(msg));
} else {
answ = data[0].some;
// this will get an array of dates: 11-11-2014,11-13-2014,11-14-2014
alert(enabledDays);
if(answ!=''){
alert(answ);
var result = answ.split(",");
//that would split the answer with the , seperator
for(i = 0; i < result.length; i++){
enabledDays.push("'"+result[i]+"'");
}
}else{
enabledDays ='';
}
}
}
}
xmlhttp.open("GET","appointments_ajax.php?actionmode="+actionmode+"&doctorid="+doctorid);
xmlhttp.send();
}
function enableAll(date) {
var m = date.getMonth() + 1, d = date.getDate(), y = date.getFullYear();
for (i = 0; i < enabledDays.length; i++) {
if($.inArray(m + '-' + d + '-' + y,enabledDays) != -1) {
return [true];
}
}
return [false];
}
$(function(){
$('#appointmentdate').datepicker({
dateFormat:'yy-mm-dd',
beforeShowDay: enableAll,
});
});
When I press the input toolbar, it will display a calendar which will be all disabled except the dates that are in the array

Trouble with JavaScript onSubmit from HTML Form

This is probably a very simple oversight on my behalf, but I cannot get the below to run.
I am triggering this function at the press of a button in a form element. If I run this outside of the getData() function it works correctly (with a manually coded URL), but trying to run the function does not work.
Could someone please take a look at this and advise where I may be going wrong?
function getData(form) {
var url = '/service/search/' + form.date.value;
var getStats = new XMLHttpRequest();
getStats.open('GET', url, true);
getStats.onload = function() {
if (getStats.status = 200) {
//Add JSON to "data"
var data = JSON.parse(getStats.responseText);
var list = '';
if (data.length > 0) {
document.getElementById('results').innerHTML += '<tr><th> </th><th>Start</th><th>End</th><th>Title</th><th> </th></tr>'
}
for (var i = 0; i < data.length; i++) {
list += '<tr data-state="'+data[i].state+'" class="'+data[i].type+'-item"><td class="crm-'+data[i].state+'"></td><td>'+data[i].start+'</td><td>'+data[i].end+'</td><td>'+data[i].title+'</td><td>View</td>';
}
//document.getElementById('results').innerHTML += list;
console.log(list);
} else {
console.error('HTTP ERROR: ' + getStats.status);
}
};
getStats.onerror = function() {
console.error('ERROR');
};
getStats.send();
}
UPDATE
As requested, this is how I am calling the function:
<form onsubmit="getData(this);">
<input type="text" placeholder="YYYY-MM-DD" id="date">
<input type="submit" value="Search">
</form>
In regards to when this works correctly, if I run the below outside of a function it works:
var url = '/service/search/2014-06-11';
var getStats = new XMLHttpRequest();
getStats.open('GET', url, true);
getStats.onload = function() {
if (getStats.status = 200) {
//Add JSON to "data"
var data = JSON.parse(getStats.responseText);
var list = '';
if (data.length > 0) {
document.getElementById('results').innerHTML += '<tr><th> </th><th>Start</th><th>End</th><th>Title</th><th> </th></tr>'
}
for (var i = 0; i < data.length; i++) {
list += '<tr data-state="'+data[i].state+'" class="'+data[i].type+'-item"><td class="crm-'+data[i].state+'"></td><td>'+data[i].start+'</td><td>'+data[i].end+'</td><td>'+data[i].title+'</td><td>View</td>';
}
//document.getElementById('results').innerHTML += list;
console.log(list);
} else {
console.error('HTTP ERROR: ' + getStats.status);
}
};
getStats.onerror = function() {
console.error('ERROR');
};
getStats.send();

json parsing using javascript

I have trouble in parsing the JSON using the Javascript.My resultant variable 'text' do does not have the result after completion of loop. Can anybody guide me how can I parse this JSON properly.
var xmlr = null;
var text = '';
if (window.XMLHttpRequest) {
xmlr = new XMLHttpRequest();
} else {
xmlr = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlr.onreadystatechange = function () {
if (xmlr.readyState == 4 && xmlr.status == 200) {
var data = JSON.parse(xmlr.responseText);
for (var i = 0; i <= data.length; i++) {
text += '<option>' + data[i].member_first_name + '</option>';
}
console.log(text); // here not get result in text
}
}
xmlr.open("GET", "data.json", true);
xmlr.send();
also content of data.json are
[
{"member_id":"3","member_first_name":"sachin ","member_last_name":"kumar"},
{"member_id":"4","member_first_name":"abhijit","member_last_name":"kumar"},
{"member_id":"5","member_first_name":"nithin","member_last_name":"ev"},
{"member_id":"6","member_first_name":"tukaram","member_last_name":"kumar"},
{"member_id":"7","member_first_name":"manish","member_last_name":"mungle"},
{"member_id":"8","member_first_name":"dsfdgfh","member_last_name":"dfgfhgfh"},
{"member_id":"9","member_first_name":"hjhgjkhkhj","member_last_name":""},
{"member_id":"10","member_first_name":"hjhkjhggf","member_last_name":""},
{"member_id":"11","member_first_name":"klkjlgfhf","member_last_name":"hjghkj"},
{"member_id":"12","member_first_name":"jkhkjhkl","member_last_name":"hgjgffhfkhj"},
{"member_id":"13","member_first_name":"hfgtjgjhg","member_last_name":"fghjgfhjg"},
{"member_id":"14","member_first_name":"hgjgfjhj","member_last_name":"hgjhgjhfg"},
{"member_id":"15","member_first_name":"cvcxvnvnbv","member_last_name":"nbvcbvc"},
{"member_id":"16","member_first_name":"vbvcnbnbm","member_last_name":"vbxgdssdg"},
{"member_id":"17","member_first_name":"lkfndbfbsd","member_last_name":"dfggfhfh"},
{"member_id":"18","member_first_name":"fghjjdfd","member_last_name":"fgfghghf"},
{"member_id":"19","member_first_name":"ghgfjhfj","member_last_name":"fghfhfd"},
{"member_id":"20","member_first_name":"dfhgfhh","member_last_name":"gdfhfd"}
]
To traverse the object array best available in java script that , traverse the object array using for/in loop than for loop, so my final code which traverse the object array as follow:-
var xmlr = null;
var text = '';
if (window.XMLHttpRequest) {
xmlr = new XMLHttpRequest();
} else {
xmlr = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlr.onreadystatechange = function () {
if (xmlr.readyState == 4 && xmlr.status == 200) {
var data = JSON.parse(xmlr.responseText);
for (var key in data) {
text += '<option>' + data[key].member_first_name + '</option>';
}
console.log(text);
}
}
xmlr.open("GET", "data.json", true);
xmlr.send();

Categories

Resources