How to display data from localstorage using handlebars? - javascript

In my program i fetch data from console and store it in localstorage and webSQL . Now i want to display the stored data from localstorage using handlebar. I used the following code:
console.log(response); // To get data from console
var offer = JSON.stringify(response);
localStorage.setItem("object",offer); // saved in localstorage
var seasons= localStorage.getItem("object"); // get data from localstorage and saved in variable seasons
var mysource = document.getElementById("detailstemplate").innerHTML;
var mytemplate = Handlebars.compile(mysource);
var myresult = mytemplate(seasons);
document.getElementById("divOffers").innerHTML = myresult;
I used the last 4 lines to display data using handlebars. But it is not working. Please correct the error.Can anyone help with this?

var season = localStorage.getItem("cart");
var season2 = $.parseJSON(season);
var mytemp = $("#mainmenu-template").html(); // Grab the template script
var ourtemp = Handlebars.compile(mytemp); // Compile the template
var resultnew = ourtemp(season2);
$("#divMainMenu").append(resultnew);

Related

Put variable name in JSON Array (fetched by an api)

I am very new to Javascript but I will try to put this in convenient way. I am having this api where I am fetching the rank of a crypto (Ripple; currently ranked 7 and is subject to change overtime ), code below:
function myFunction() {
var url = "https://api.coinpaprika.com/v1/coins/xrp-xrp";
var XRPresponse = UrlFetchApp.fetch(url);
var XRPjson = XRPresponse.getContentText();
var XRPdata = JSON.parse(XRPjson);
var XRPrank = XRPdata.rank;
}
Now this is another function for an api where I extract other infos (having 5000+ crytos listed, including ripple)
function myXRP() {
var url = "https://api.coinpaprika.com/v1/tickers";
var response = UrlFetchApp.fetch(url);
var json = response.getContentText();
var data = JSON.parse(json);
var XRP = data[7].symbol;
// Here instead of [7], I need to put the value extracted from XRPrank above so that whenever the rank is changed I get the latest value on data.[].
If someone could please advise.
In JavaScript there are several ways to achieve what you are looking for. The following is an adaptation of your current code with what I think are the minimal changes that you have to do, 1. use return followed by XRPrank 2. Call myFunction from myXRP and replace the data index by XRPrank.
function myFunction() {
var url = "https://api.coinpaprika.com/v1/coins/xrp-xrp";
var XRPresponse = UrlFetchApp.fetch(url);
var XRPjson = XRPresponse.getContentText();
var XRPdata = JSON.parse(XRPjson);
var XRPrank = XRPdata.rank;
return XRPrank; // add this
}
function myXRP() {
var url = "https://api.coinpaprika.com/v1/tickers";
var response = UrlFetchApp.fetch(url);
var json = response.getContentText();
var data = JSON.parse(json);
var XRPrank = myFunction(); // add this
// var XRP = data[7].symbol; instead of this
var XRP = data[XRPrank].symbol; // use this
}
Resources
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions

Save data to cache using PHP

I'm working on an api, which I get the data from the db then display as json. The data is big and increases every second, I manage to lessen the load by saving it in localStorage on first load then just load the latest data on next fetch then add it to the localStorage. My problem is, it reached the max size of data. Is there a way to do it on php?
JS
if(index == 0){
localStorage.setItem("figureChart1-"+aid, JSON.stringify(data));
var arrseries1 = data['B5'];
var arrseries2 = data['B6'];
var datetime = data['datetime'];
} else {
var chart1Json = JSON.parse( localStorage.getItem( 'figureChart1-'+aid ) );
var obj = {};
obj['id'] = chart1Json['id'].concat(data['id']);
obj['datetime'] = chart1Json['datetime'].concat(data['datetime']);
obj['B5'] = chart1Json['B5'].concat(data['B5']);
obj['B6'] = chart1Json['B6'].concat(data['B6']);
localStorage.setItem("figureChart1-"+aid, JSON.stringify(obj));
var arrseries1 = obj['B5'];
var arrseries2 = obj['B6'];
var datetime = obj['datetime'];
}

How to update multiple fields in Firebase Web?

I have the following code where I want to update some simple values in my Firebase database using the JavaScript, Web SDK.
However, it doesn't run/update my database. What's wrong here?
var dbRef = firebase.database().ref().child('feeds').child(selectedFeed).child('audio');
var uid = dbRef.push().key;
var data = {
"downloadURL": uploadTask.snapshot.downloadURL,
"fileName": file.name,
"timeStamp": selectedDateUnix
};
var updates = {};
updates["mostRecentKey"] = uid;
updates[uid] = data;
dbRef.update(updates).then(function(){
//success
alert("Successfully Uploaded. This is now available to be listened to by your users.");
}).catch(function(error){
//failure
alert(error.message);
});
While it doesn't ever specify in the Firebase docs and actually I felt indicated it wasn't required; You MUST cast your data. For example:
This does not work. Directly accessing the variable.
var myNum = 10;
var data = {};
data["myNum"] = myNum;
This does work, but doesn't allow a dynamic use of a var.
var data = {};
data["myNum"] = 10;
Finally, this works and was my solution using a variable reference. Cast your data.
var myNum = 10;
var data = {};
data["myNum"] = Number(myNum);

Apps script write to Big Query unknown error

This is supposed to read in a CSV and then write it to bigquery. When it runs, however, nothing is written, and there are no errors logged. I read that I need to write a csv and then turn it into an Octet Stream. I am not sure whether or not this is compatible with google bigquery.
function test(){
try{
var tableReference = BigQuery.newTableReference();
tableReference.setProjectId(PROJECT_ID);
tableReference.setDatasetId(datasetId);
tableReference.setTableId(tableId);
var schema = "CUSTOMER:string, CLASSNUM:integer, CLASSDESC:string, CSR:string, CSR2:string, INSURANCE:string, REFERRALGENERAL:string, REFERRALSPECIFIC:string, NOTES:string, INMIN:integer, INHR:integer, OUTMIN:integer, OUTHR:integer, WAITMIN:integer, WAITHR:integer, DATETIMESTAMP:float, DATEYR:integer,DATEMONTH:integer, DATEDAY:integer";
var load = BigQuery.newJobConfigurationLoad();
load.setDestinationTable(tableReference);
load.setSourceUris(URIs);
load.setSourceFormat('NEWLINE_DELIMITED_JSON');
load.setSchema(schema);
load.setMaxBadRecords(0);
load.setWriteDisposition('WRITE_TRUNCATE');
var configuration = BigQuery.newJobConfiguration();
configuration.setLoad(load);
var newJob = BigQuery.newJob();
newJob.setConfiguration(configuration);
var loadr = DriveApp.getFilesByName("test.csv");
var x = loadr.next().getBlob();
Logger.log(x.getDataAsString());
var d = DriveApp.getFilesByName("test.csv");
var id = d.next().getId();
Logger.log(id);
var data = DocsList.getFileById(id).getBlob().getDataAsString();
var mediaData = Utilities.newBlob(data, 'application/octet-stream');
BigQuery.Jobs.insert(newJob, PROJECT_ID, mediaData)
}
catch(error){Logger.log("A" + error.message);}
}
Your sourceFormat is wrong for CSV files:
The format of the data files. For CSV files, specify "CSV". For
datastore backups, specify "DATASTORE_BACKUP". For newline-delimited
JSON, specify "NEWLINE_DELIMITED_JSON". The default value is CSV.
https://developers.google.com/bigquery/docs/reference/v2/jobs#configuration.load.sourceUris
On the other hand I think you don't need at all the load.setSourceUris(URIs); since you try to load from local file, and not from Google Cloud Storage. Check this python example https://developers.google.com/bigquery/loading-data-into-bigquery

Titanium mobile - Uncaught Error: no such table

I am having a terrible time trying to figure out why I keep getting this error. I have searched this and other forums and no answer seems to be able to help so I will ask here.
I am trying to create a basic photo catalogue app for Android using Titanium. The catalogue info is strore in an sqlite database.
I can create the database OK - I can access some info from it in one window. When I then go to another window and try to get further info from the table it gives me the error:
Uncaught error: no such table: photos:, while compiling SELECT..........
See code below:
This is the first window that opens from app.js
The table shows up fine here - NO errors
// create var for the currentWindow
var currentWin = Ti.UI.currentWindow;
// set the data from the database to the array
//function setData() {
// create table view
var tableview = Ti.UI.createTableView({
});
//var db = Ti.Database.open('catalogue');
//db.remove();
var db = Ti.Database.install('catalogue.sqlite','photos');
var rows = db.execute('SELECT * FROM photos GROUP BY title');
// create the array
var dataArray = [];
while(rows.isValidRow()) {
var title = rows.fieldByName('title');
var id = rows.fieldByName('id');
dataArray.push({title:title, id:id, url:'catalogue_detail.js'});
rows.next();
}
tableview.setData(dataArray);
// add the tableView to the current window
currentWin.add(tableview);
tableview.addEventListener('click', function(e){
if (e.rowData.url)
{
var win = Ti.UI.createWindow({
id:e.rowData.id,
title:e.rowData.title,
url:e.rowData.url
});
win.open();
}
});
// call the setData function to attach the database results to the array
//setData();
I then open catalogue_detail.js from the above and I get the error
catalogue_detail.js
var win = Titanium.UI.currentWindow;
var id = win.id
var tableview = Titanium.UI.createTableView({
});
var db = Titanium.Database.open('catalogue.sqlite');//I have chanegd this to 'photos' and I get the same error
var sql = db.execute('SELECT title, location, photographer FROM photos where id="' + id + '"');
var title = sql.fieldByName('title');
var location = sql.fieldByName('location');
var photographer = sql.fieldByName('photographer');
// create the array
var dataArray = [];
while(sql.isValidRow()) {
var title = sql.fieldByName('title');
var location = sql.fieldByName('location');
var photographer = sql.fieldByName('photographer');
dataArray.push({title:title, location:location, photographer:photographer});
sql.next();
}
tableview.setData(dataArray);
win.add(tableview);
So the table in my database called 'photos' open in one window then I get the error trying to open the same database?
I have uninstalled the app, recreated the database, renamed tables etc but still the same error...
I am sure it is a simple thing I am missing but I am very confused!
Thanks for any assistance.
JC
Try absolute path: Ti.Database.open('catalogue.sqlite'); and Ti.Database.install('/catalogue.sqlite');.
Also remember about closing connection to database when you retrieve all data from query:
sql.close();
db.close();

Categories

Resources