How to re-pull from file if data changes in NodeJS? - javascript

My javascript is currently pulling JSON data from a server I made in NodeJS. The data is coming from a google spreadsheet, so whenever I make changes to the spreadsheet the JSON data changes too.
I do not want to have to refresh my site to apply the updated spreadsheet data. How can I pull from the JSON file every time there is a change made? Someone mentioned using timestamps on the file and if the time stamp changes, then pull from the file. But I could not find an example.
Right now I am pulling data from the /latest route in my node server to my javascript. Code below:
app.get('/latest', function(req,res) {
var fs = require('fs');
var obj;
fs.readFile('public/announcementCurrent.json', function (err, data) {
if (err) throw err;
obj = JSON.parse(data);
res.json(obj)
});
})
This is how I call the route in my javascript:
$http.get('http://localhost:3000/latest')
How can I call the route again when the announcementCurrent.json file changes without having to refresh?
Any help would be great thanks!

The way to get updated data in real time in javascript without having to refresh the page is the whole idea of XMl Http requests, aka AJAX.
Basically you will need, at some time interval or user action of your choice, query the Google API to get the latest data and update your page accordingly.
You should try to get more informations about how to make an ajax call, and how to query the google spreadsheet API. Basically, using jQuery for instance (hum), it would look like:
$.get('http://google-spreadsheet-api-url', function( data ) {
// Dynamically refresh the content of the page using data
})

Related

How to bind the Stored Annotation for pdf

I am using annotator.js to annotate my PDF documents. I am able to save it to my SQL database and retrieve it. But I am not sure how to Bind back the data on to the specific page. I am using Pure HTML, JQuery for the AnnotatorJS API calls and REST web service to send and receive data in JSON format.
My problem is what are the steps required to use the retrieved data from my SQL database and bind it on to the PDF.
Any suggestions?
I had similar problem before. Try this code. You can change your code accordingly
var subscription= $('#content').annotator();
subscription.data('annotator').plugins['Store'].loadAnnotationsFromSearch().then(function(res) {
subscription.annotator('loadAnnotations', res.rows); res.rows /// in my case
});

Converting an HTML table to JSON to pass to an AJAX call for downloading as a CSV

I am having to write a reporting system in ASP classic.
The people who wrote the wireframe have no concept of performance/speed/how SQL works and so forth so I have lots of fun just getting the data out of the DB.
However they want to have buttons the users can press to "download" the report to a CSV file.
I could submit the form and re-run the SQL (which takes a long time due to the number of reports shown on one page and their format) - and then just send it to the browser as a file.
OR I was thinking of using JS or jQuery etc to take the desired table of contents, somehow convert that to a JSON object, post that to another page using AJAX and then in that other page take the JSON and decode it into a CSV format which can then be delivered to the user as a file.
I just think this JS approach would be quicker and also if I could make it generic so it could take any table with a class on it e.g "report" and convert that into a JSON object that would be used to create a CSV I could easily re-use this code on the hundreds of reports they have made me write.
Does anyone have an JavsaScript code or jQuery that would take a table in any format (it has a thead with column headers, the a tbody with the main contents) and encode it to a JSON or JS object for posting to another page where I could then de-encode it and pipe it out as a CSV file?
Here is a screen shot of one of their reports,
A possible solution to the problem could be to already generate the CSV formatted version of the data for each report when the page that displays the given report is requested. (Database is only queried once per report.) Send the data back in the response in the expected format to display it in the table and save the CSV file to a temporary location on the server.
This way you can place a link near the table 'download CSV' which will point to the already existing file. It will avoid having to query the same data twice for one report OR to having to send the same data to a roundtrip between server and client.
Javascript doesn't provide a way to save text to a file, so you would still have to do that server-side, i.e. by AJAX as you already suggested.
With jQuery you could do something like this (not tested), and send it via an AJAX request.
var headers = [];
$('table.report thead > tr > th').each(function($i, obj) { //or <td> instead of <th>
headers.push($(obj).text());
});
var data = [];
$('table.report tbody > tr').each(function($i, tr) {
var row = [];
$(tr).find('th').each(function($h, td) {
row[headers[$h]] = td.text();
});
data.push(row);
});
var json = JSON.stringify(data);
However I don't think this is the preferable way, because it's still user-input. I could put some random data in a POST and get a CSV in return.
A better way would be to cache your data you already have, and create a CSV file from the cached data when requested.

how to create a file and write some output to it from server side java script

I am new to java script. I have execute some API from server-side java script and stored their status in a array now i want to create a file at desired location on same machine and write output to it.
You must have to use server-side language to do this js won't do that!
Lets take the example of the ASP.NET
#{
var userData = /* data stored in the array */
var dataFile = Server.MapPath("~/App_Data/data.txt"); // file location
File.AppendAllText (#dataFile, userData); // save it!
}
This way, you will be able to save the data in the file on the server-side. If you wanted to save it without reloading the page (like many developers love to) then you can try using ajax request. For that, you will be using jQuery AJAX but still to write the data to a file you will require the server-side. Here
$.ajax({
url: 'url/where/file_is.txt'
});
And the in page, you will have the server-side code which will
Get the array data
Split it relatively
Write it to the file.
This way you will have the user's data written to the file.
For more: http://www.asp.net/web-pages/tutorials/files,-images,-and-media/working-with-files
If you're using PHP, you can do a Google search for that!

caching images & data with phonegap locally

I have a phonegap app using slim with ajax front. When I listing a certain page, I would like to cache the data and then just use that till user refreshes or sends a trigger for new data.
so far I have this for caching json data:
//caches the JSON data into localstorage
try {
localStorage.setItem('cachedProducts', JSON.stringify(data));
JSON.parse(localStorage.getItem('cachedProducts'));
var bar = localStorage.getItem('cachedProducts');
clog(bar);
} catch (e) {
clog("didn't work");
}
it works. but i have no idea how to save images or how to trigger the server for new data. thank you.
If your need is to save small number of image then you can convert it in to base64 string and store it in to local storage. You can covert images in to base64 string using canvas. If user tries to refresh the content then you connect to the server and cache the latest content.

send predefined data to browser local storage with .crx

I am building my first chrome extension, for that I want to have some predefined data at client browser.
I want that data be able to be edited by user by means of extension and save back the changes.
I first thought of using HTML5 local database or Indexed Database APIfor this.(Am I doing right?)
But I don't know how can I send this local database to client place in .crx..because the database will be with browser rather than extension.
How can I send data to client side browser by .crx and save the data on browser?
(I know its not right to save data on browser, but I can't save data back if I save data along with extension)
What other way I can use to implement the requirement?
can I use the same method if I want to use Indexed Database API instead?
My data is not simple key value pair but table kind of data.
I don't have any code for data access part, because I want to be sure before I can proceed
No, You can't send database file with ctx file. Simply You can't replace it on client side.
Actually you have two options:
1) save predefined data into your extension (in any extension file. save whole query or data as JSON) and after first run exec those query to local Database.
2) create web service from where you will get predefined data and save it to local DB.
For example (data.json):
[{"name":"name", "desc":"desc","some_column":"some value"},{"name":"name", "desc":"desc","some_column":"some value"}, ...]
In background.html:
var xhr = new XMLHttpRequest();
xhr.open('GET', chrome.extension.getURL('data.json'), false);
var dataStr = xhr.send(); //don't do this way. use asynch api :)
var data = JSON.parse(dataStr);
//connect to local database
for(var _item in data){
//create query to insert data into DB
//and exequte query
}

Categories