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?
Related
I'm trying to return two values in GAS like this:
Html
<script>
function phoneSearch() {
var phone = document.getElementById("phone").value;
google.script.run.withSuccessHandler(onSuccess).phoneSearch(phone);
}
function onSuccess(name, email) {
document.getElementById('nameDiv').innerHTML = "<div>" + name + "</div>";
document.getElementById('emailDiv').innerHTML = "<div>" + email+ "</div>";
}
</script>
Server JS
function phoneSearch(phone){
try {
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName("sheetNameHere");
var data = sheet.getDataRange().getValues();
for (var i = 1; i < data.length; i++) {
if (data[i][4] == phone) {
var name = inputData[i][3];
var email = inputData[i][5];
return name;
return email;
}
}
} catch(e) {
alert(e)
}
}
Only the first value (name) returns. Thanks in advance!
You can't use more one 'return' at the same level, you should return object containing your two values.
return {
phone: phone,
email: email
}
You can only return 1 value from your function at a time, but you can easily wrap that in an object:
<script>
function phoneSearch() {
var phone = document.getElementById("phone").value;
google.script.run.withSuccessHandler(onSuccess).phoneSearch(phone);
}
function onSuccess(result) {
// ^ phoneSearch now returns -one- object, containing `name` and `email`.
document.getElementById('nameDiv').innerHTML = "<div>" + result.name + "</div>";
document.getElementById('emailDiv').innerHTML = "<div>" + result.email+ "</div>";
}
</script>
JS
function phoneSearch(phone){
try {
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName("sheetNameHere");
var data = sheet.getDataRange().getValues();
for (var i = 1; i < data.length; i++) {
if (data[i][4] == phone) {
var name = inputData[i][3];
var email = inputData[i][5];
// Return both values at once.
return { name, email };
// (This is shorthand for: `return { name: name, email: email };`)
}
}
} catch(e) {
alert(e)
}
}
I'm binding data to 3 dropdowns by calling a method from another file of javascript. The data source of dropdown loading from IndexedDB.
Data binding JS,
function bindStateData(){
getMstStates("#state");
getMstStates("#drstate");
getMstStates("#cstate");
}
Database manager js,
function getMstStates(state) {
var request = indexedDB.open('AppDatabase', '3')
request.onsuccess = function (e) {
var dbInstance = e.target.result;
let transaction = dbInstance.transaction("MstStates", "readonly");
const statesDetailsStore = transaction.objectStore("MstStates");
stateData = statesDetailsStore.getAll();
stateData.onsuccess = function () {
var MstStatesMap = new Object();
var len = stateData.result.length,
i;
for (i = 0; i < len; i++) {
MstStatesMap[i] = {};
MstStatesMap[i].StateId = stateData.result[i].StateId;
MstStatesMap[i].StateName = stateData.result[i].StateName;
}
callBackOptionItems(MstStatesMap, state);
}
stateData.onerror = function () {
console.log('getMstStates : ' + e);
}
}
request.onerror = function (e) { console.log('getMstStates : ' + e); }
}
function callBackOptionItems(MstOptionMap, objID) {
for (var j in MstOptionMap) {
var k, v
var tem = 0;
for (var i in MstOptionMap[j]) {
if (tem == 0) {
k = MstOptionMap[j][i]
} else {
v = MstOptionMap[j][i];
}
tem++
}
var el = $(objID);
$(el).append('<option value="' + k + '">' + v + '</option>');
}
if (objID == '#select-history') {
$("#select-history").append('<option value="4">Other</option>');
}
}
When I tried to loading data I got the following error,
Uncaught DOMException: Failed to read the 'result' property from 'IDBRequest': The request has not finished.
at IDBRequest.stateData.onsuccess
The same code logic was written in WebSQL, it was running properly, but unfortunately from iOS 13 version websql support has been revoked.
I have resolved this issue. The main culprit line is,
var len = stateData.result.length;
The correct code is as follows,
var _request = statesDetailsStore.getAll();
_request.onsuccess = function (event) {
var MstStatesMap = new Object();
var stateData = event.target.result;
}
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 .
I have a basic electron app where I am trying to use vendor supplied js library. The example they supplied provides a static html page which includes their custom library and an example js file. This is the html
<HTML>
<HEAD>
<TITLE> MWD Library </TITLE>
</HEAD>
<BODY>
<h2>MWD Library Example</h2>
<input id="authAndConnect" type="button" value="authenticate and connect to stream" onclick="authenticateAndConnectToStream()" /></br></br>
<input id="clickMe" type="button" value="place position" onclick="placePosition()" /></br></br>
<input id="unsubscribeMe" type="button" value="unsubscribe" onclick="unsubscribe()" />
<input id="streamError" type="button" value="reconn to stream" onclick="reconnectToStream()" />
<input id="historicalData" type="button" value="historical data for GOLD" onclick="getHistoricalData()" />
<input id="goldExpiries" type="button" value="expiries for GOLD" onclick="getCurrentGoldExpiries()" /></br></br>
<input id="userTrades" type="button" value="active&completed trades" onclick="getUserTrades()" />
</BODY>
<SCRIPT SRC="jquery.ajax.js"></SCRIPT>
<SCRIPT SRC="mwdlib.js"></SCRIPT>
<SCRIPT SRC="app.js"></SCRIPT>
</HTML>
In the example above the button click calls authenticateAndConnectToStream in their example apps.js
//DEMO
//provide API key
MWDLibrary.config("dwR4jXn9ng9U2TbaPG2TzP1FTMqWMOuSrCWSK5vRIW7N9hefYEapvkXuYfVhzmdyFypxdayfkUT07HltIs4pwT0FIqEJ6PyzUz0mIqGj1GtmAlyeuVmSC5IcjO4gz14q");
//authenticate on MarketsWorld
var getAuthTokenParams = {email:"rtmarchionne#gmail.com", password:"Pitts4318AEM"};
var authenticateAndConnectToStream = function(){
MWDLibrary.getAuthDetails(getAuthTokenParams, function(authDetails) {
//optional: get older data
var marketsToSubscribeTo = ['GOLD', 'AUDNZD'];
for (var i = 0; i < marketsToSubscribeTo.length; i++){
MWDLibrary.getHistoricalData(marketsToSubscribeTo[i], function(response) {
console.log(response);
}, function(errorMessage) {
console.log(errorMessage);
});
}
//now you can connect to stream
MWDLibrary.connect(marketsToSubscribeTo, function() {
addMarketsListeners();
}, function(errorMessage) {
console.log(errorMessage);
});
}, function(errorMessage) {
console.log(errorMessage);
});
};
I want to call the same methods that start with MWDLibrary. from my main js like MWDLibrary.config("dwR4jXn9")
My main.js:
const electron = require('electron')
var path = require('path');
var countdown = require(path.resolve( __dirname, "./tradescaler.js" ) );
var mwd = require(path.resolve( __dirname, "./mwdlib.js" ) );
const app = electron.app
const BrowserWindow = electron.BrowserWindow
const ipc = electron.ipcMain
let mainWindow
app.on('ready', _ => {
mainWindow = new BrowserWindow({
height: 360,
width: 700,
title: "TradeScaler Beta - Creative Solutions",
//frame: false,
alwaysOnTop: true,
autoHideMenuBar: true,
backgroundColor: "#FF7E47",
})
mainWindow.loadURL('file://' + __dirname + '/tradescaler.html')
mainWindow
//mainWindow.setAlwaysOnTop(true, 'screen');
mainWindow.on('closed', _ => {
mainWindow = null
})
})
ipc.on('countdown-start', _ => {
console.log('caught it!');
MWDLibrary.config();
countdown(count => {
mainWindow.webContents.send('countdown', count)
})
})
In my main.js above I get an error that says MWDLibrary is not defined.
Is it the structure of the library that is the problem? do i have to pass a window or modify the library?
Here is the library I'm trying to use:
(function(window){
'use strict';
function init(){
var MWDLibrary = {};
var transferProtocol = "https://"
var streamTransferProtocol = "https://"
var baseTLD = "www.marketsworld.com"
var basePort = ""
var streamBaseTLD = "www.marketsworld.com"
var streamPort = ""
var authToken = "";
var publicId = "";
var userLevel = "user";
var apiKey = "-";
var streamUrl = "";
var streamToken = "";
var subscribedChannels = [];
var streamEvents = {};
var offersWithExpiries = [];
var filteredExpiries = {};
var positions = {};
var evtSource;
MWDLibrary.config = function(apiUserKey){
apiKey = apiUserKey;
}
MWDLibrary.expiries = function(market){
return filteredExpiries[market];
}
MWDLibrary.connect = function(channelsToSubscribeTo, successHandler, errorHandler){
//console.log("Connecting...");
if(publicId === ""){
errorHandler("Please authenticate first.");
return;
}
var dispatchUrl = streamTransferProtocol+streamBaseTLD+streamPort+'/api/dispatcher';
getJSON(dispatchUrl, apiKey, authToken, function(data){
var data_from_json = JSON.parse(data);
if(data_from_json.url){
var url = data_from_json.url+'/announce?callback=__callback&publicToken='+publicId+'&userLevel='+userLevel+'&_='+(new Date().getTime() / 1000);
getJSON(url, apiKey, authToken, function(data) {
var data_from_json = JSON.parse(data);
if(data_from_json.url){
streamUrl = data_from_json.url.substring(0,data_from_json.url.lastIndexOf("/user"));
streamToken = data_from_json.url.split("token=")[1];
MWDLibrary.subscribe(channelsToSubscribeTo, function(subscribeResponseData) {
evtSource = new EventSource(streamTransferProtocol+data_from_json.url);
evtSource.onopen = sseOpen;
evtSource.onmessage = sseMessage;
evtSource.onerror = sseError;
successHandler('connected');
return;
}, function(errorMessage) {
errorHandler(errorMessage);
return;
});
}
else{
//console.log(data);
errorHandler('Something went wrong.');
return;
}
}, function(status) {
//console.log(status);
errorHandler(status);
return;
});
}
else{
//console.log(data);
errorHandler('Something went wrong.');
return;
}
}, function(status) {
//console.log(status);
errorHandler(status);
return;
});
}
MWDLibrary.subscribe = function(channelsToSubscribeTo, successHandler, errorHandler){
//console.log("Subscribing...");
if(publicId === ""){
errorHandler("Please authenticate first.");
return;
}
var channels = 'ALL|TEST|private.'+publicId;
if (channelsToSubscribeTo.length > 0){
var auxChannels = '';
if(subscribedChannels.length > 0){
channels = subscribedChannels[0];
for(var j = 1; j < subscribedChannels.length; j++){
channels = channels +'|'+subscribedChannels[j];
}
}
for(var i = 0; i < channelsToSubscribeTo.length; i++)
{
if(subscribedChannels.indexOf(channelsToSubscribeTo[i])==-1){
auxChannels = auxChannels+'|'+channelsToSubscribeTo[i]+'|'+channelsToSubscribeTo[i]+'.game#1';
}
}
channels = channels+auxChannels;
}
else{
if (subscribedChannels.length == 0)
{
channels = channels+'|GOLD|GOLD.game#1';
}
else{
channels = subscribedChannels[0];
for (var j = 1; j < subscribedChannels.length; j++){
channels = channels + '|' + subscribedChannels[j];
}
}
}
var subscribeUrl = streamTransferProtocol+streamUrl+'/user/stream/subscribe?callback=__callback&token='+streamToken+'&channels='+escape(channels)+'&_='+(new Date().getTime() / 1000);
//subscribe to channels
getJSON(subscribeUrl, apiKey, authToken, function(subscribeData) {
var subscribeData_from_json = JSON.parse(subscribeData);
subscribedChannels = subscribeData_from_json.channels;
//console.log(subscribedChannels);
for (var i = 0; i < subscribedChannels.length; i++)
{
if (subscribedChannels[i] == 'ALL')
{
streamEvents[subscribedChannels[i]] = {};
streamEvents[subscribedChannels[i]]['heartbeat'] = new CustomEvent('ALL.heartbeat', {'detail':'-'});
streamEvents[subscribedChannels[i]]['status'] = new CustomEvent('ALL.status', {'detail':'-'});
continue;
}
if (subscribedChannels[i].lastIndexOf('private') > -1)
{
streamEvents[subscribedChannels[i]] = {};
streamEvents[subscribedChannels[i]]['positions'] = new CustomEvent('PRIVATE.positions', {'detail':'-'});
streamEvents[subscribedChannels[i]]['balance'] = new CustomEvent('PRIVATE.balance', {'detail':'-'});
continue;
}
if (subscribedChannels[i].lastIndexOf('game') > -1)
{
streamEvents[subscribedChannels[i]] = {};
streamEvents[subscribedChannels[i]]['expiry'] = new CustomEvent(subscribedChannels[i].split('.')[0]+'.expiry', {'detail':'-'});
streamEvents[subscribedChannels[i]]['spread'] = new CustomEvent(subscribedChannels[i].split('.')[0]+'.spread', {'detail':'-'});
streamEvents[subscribedChannels[i]]['payout'] = new CustomEvent(subscribedChannels[i].split('.')[0]+'.payout', {'detail':'-'});
streamEvents[subscribedChannels[i]]['offer'] = new CustomEvent(subscribedChannels[i].split('.')[0]+'.offer', {'detail':'-'});
continue;
}
streamEvents[subscribedChannels[i]] = {};
streamEvents[subscribedChannels[i]]['value'] = new CustomEvent(subscribedChannels[i]+'.value', {'detail':'-'});
}
successHandler(subscribeData_from_json);
}, function(status) {
errorHandler(status);
});
}
MWDLibrary.unsubscribe = function(channelsToUnsubscribeFrom, successHandler, errorHandler){
//console.log("Unsubscribing...");
if(publicId === ""){
errorHandler("Please authenticate first.");
return;
}
if(channelsToUnsubscribeFrom.length == 0){
errorHandler("Please select markets to unsubscribe from.");
return;
}
var channels = channelsToUnsubscribeFrom[0]+'|'+channelsToUnsubscribeFrom[0]+'.game#1';
for(var i = 1; i < channelsToUnsubscribeFrom.length; i++)
{
channels = channels+'|'+channelsToUnsubscribeFrom[i]+'|'+channelsToUnsubscribeFrom[i]+'.game#1';
}
var subscribeUrl = streamTransferProtocol+streamUrl+'/user/stream/unsubscribe?callback=__callback&token='+streamToken+'&channels='+escape(channels)+'&_='+(new Date().getTime() / 1000);
//subscribe to channels
getJSON(subscribeUrl, apiKey, authToken, function(unsubscribeData) {
var unsubscribeData_from_json = JSON.parse(unsubscribeData);
var unsubscribedChannels = unsubscribeData_from_json.channels;
for(var i = 0; i < unsubscribedChannels.length; i++)
{
var index = subscribedChannels.indexOf(unsubscribedChannels[i]);
if(index != -1) {
subscribedChannels.splice(index, 1);
}
}
//console.log(subscribedChannels);
successHandler(unsubscribeData_from_json);
}, function(status) {
errorHandler(status);
});
}
MWDLibrary.getAuthDetails = function(params, successHandler, errorHandler){
//console.log("getting auth token...");
var url = transferProtocol+baseTLD+basePort+'/api/v2/sessions';
postJSON(url, apiKey, authToken, params, function(data) {
var data_from_json = JSON.parse(data);
if (!data_from_json.error){
authToken = data_from_json.api_session_token.token;
publicId = data_from_json.api_session_token.user.public_id;
successHandler(data_from_json.api_session_token);
return;
}
else{
errorHandler(data_from_json.error);
return;
}
}, function(status) {
errorHandler(status);
return;
});
}
MWDLibrary.placePosition = function(params, successHandler, errorHandler){
//console.log("placing a position...");
if(publicId === ""){
errorHandler("Please authenticate first.");
return;
}
var url = transferProtocol+baseTLD+basePort+'/api/v2/positions';
if(params.market == ''){
errorHandler('Market code is missing.');
return;
}
var position = positions[params.market];
if(!position || position.market_value <= 0){
errorHandler('No data for this market.');
return;
}
if(!params.offer_id || params.offer_id == ''){
errorHandler('Offer id is missing.');
return;
}
if(!params.resolution_at || params.resolution_at <= 0){
errorHandler('Expiry time is missing.');
return;
}
if(!params.type || params.type == ''){
errorHandler('Position type is missing.');
return;
}
if(!params.wager || params.wager <= 0){
errorHandler('Wager is missing.');
return;
}
position.offer_id = params.offer_id;
position.resolution_at = params.resolution_at;
position.type = params.type;
position.wager = params.wager;
//console.log(position);
postJSON(url, apiKey, authToken, position, function(data) {
var data_from_json = JSON.parse(data);
if (!data_from_json.error){
successHandler(data_from_json);
return;
}
else{
errorHandler(data_from_json.error);
return;
}
}, function(status) {
errorHandler(status+' - make sure all parameters are set correctly and wait 10 seconds between bets');
return;
});
}
MWDLibrary.getMarkets = function(successHandler, errorHandler){
//console.log("getting markets list...");
getJSON(transferProtocol+baseTLD+basePort+'/api/v2/markets.json', apiKey, authToken, function(data) {
var data_from_json = JSON.parse(data);
for (var i = 0; i < data_from_json.length; i++) {
var status = "closed";
if (data_from_json[i].market.next_open_time > data_from_json[i].market.next_close_time)
{
status = "open";
}
data_from_json[i].market.status = status;
}
successHandler(data_from_json);
}, function(status) {
errorHandler(status);
});
}
var sortedOffersWithExpiries = offers.sort(compareOffersBtOrder);
for (var i=0; i<sortedOffersWithExpiries.length;i++)
{
expiryValue = 0;
expiryResult = 0;
var expiriesCopy = sortedOffersWithExpiries[i].expiries;
for (var index = 0; index<expiriesCopy.length;index++)
{
expiryValue = expiriesCopy[index]
if (expiryValue > lastExpiry)
{
expiryResult = expiryValue
break
}
}
if (expiryResult != 0)
{
var tuple = {};
tuple.timestamp = expiryValue/1000;
tuple.offerId = sortedOffersWithExpiries[i].offer;
tuple.cutout = sortedOffersWithExpiries[i].cutout;
expiriesFinalList.push(tuple);
lastExpiry = expiryValue
}
}
return expiriesFinalList;
}
function compareOffersBtOrder(a,b) {
if (a.order < b.order)
return -1;
if (a.order > b.order)
return 1;
return 0;
}
})/*(window)-->*/;
You're missing the .js file extension at the end of mwdlib
And you may need to require it using the full system path, instead of a relative one.
var mwd = require(path.resolve( __dirname, "./mwdlib.js" ) );
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();