Log client browse website information in backbone.js - javascript

I'm using this code to get client information :
$.getJSON("http://www.geoplugin.net/json.gp?jsoncallback=?",function (data) {
console.log(data.geoplugin_request);
console.log(data.geoplugin_countryName);
});
Then I would like to record this information at the first time that client visit the website (session start of the website). My current project are using backbone.js, require.js, underscore.js.
Any suggestions would be appreciated. Thanks.

Assuming that you have application.js file which act as a entry point of the backbone aplication which initializes your router an all stuff, you can set the client details in the browser using localStorage.
// Retrieve the object from storage
var retrievedVar = localStorage.getItem('countryName');
if( retrievedVar == null) {
$.getJSON("http://www.geoplugin.net/json.gp?jsoncallback=?",function (data) {
console.log(data.geoplugin_countryName);
// Put the object into storage
localStorage.seItem('countryName', JSON.stringify(data.geoplugin_countryName)
});
Hence the getJSON will only be fired once when localStorage var is not set.

Related

How to get data from back end side, to use it in the browser side?

I am new to programming, and I heard that some guys on this website are quite angry, but please don't be. I am creating one web app, that has a web page and also makes som ecalculations and works with database (NeDB). I have an index.js
const selects = document.getElementsByClassName("sel");
const arr = ["Yura", "Nairi", "Mher", "Hayko"];
for (let el in selects) {
for (let key in arr) {
selects[el].innerHTML += `<option>${arr[key]}</option>`;
}
}
I have a function which fills the select elements with data from an array.
In other file named: getData.js:
var Datastore = require("nedb");
var users = new Datastore({ filename: "players" });
users.loadDatabase();
const names = [];
users.find({}, function (err, doc) {
for (let key in doc) {
names.push(doc[key].name);
}
});
I have some code that gets data from db and puts it in array. And I need that data to use in the index.js mentioned above, but the problem is that I don't know how to tranfer the data from getData.js to index.js. I have tried module.exports but it is not working, the browser console says that it can't recognize require keyword, I also can't get data directly in index.js because the browse can't recognize the code related to database.
You need to provide a server, which is connected to the Database.
Browser -> Server -> DB
Browser -> Server: Server provides endpoints where the Browser(Client) can fetch data from. https://expressjs.com/en/starter/hello-world.html
Server -> DB: gets the Data out of the Database and can do whatever it want with it. In your case the Data should get provided to the Client.
TODOs
Step 1: set up a server. For example with express.js (google it)
Step 2: learn how to fetch Data from the Browser(Client) AJAX GET are the keywords to google.
Step 3: setup a Database connection from you Server and get your data
Step 4: Do whatever you want with your data.
At first I thought it is a simple method, but them I researched a little bit and realized that I didn't have enough information about how it really works. Now I solved the problem, using promises and templete engine ejs. Thank you all for your time. I appreciate your help)

How do I set up a JSON data set that can be accessed offline?

I am trying to build a mobile application with multiple pages that users can use and navigate offline. It will have a search function to look for certain pages within itself. In previous questions I was told setting up JSON data sets is the best way to do this; however, every example or tutorial or book I read about JSON data sets and accessing them all have to do with come communication with a server and browser. How would I set up the JSON data set and set up the ability for users to interact with it or call in via to access the JSON data set offline? I just assume that it would be different than setting it up like the examples I've seen so far
You can use localStorage to store the JSON data in the browser.
Let's say you have a file on the server called data.json with the following content:
[{ "name":"Name1", "surname":"Surname1" },
{ "name":"Name2", "surname":"Surname2"},
{ "name":"Name3", "surname":"Surname3" },
{ "name":"Name4", "surname":"Surname4" }]
When a user access the mobile application for the first time you can make a call to the server,get the JSON data and store it in the browser using localStorage:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$.getJSON("data.json", function (data) {
localStorage.setItem('users', JSON.stringify(data));
});
});
</script>
Google Chrome -> Resource -> Local Storage:
Now that your JSON object is stored locally you can retrieve it from local storage and use it in your application without connecting to the server.Just make sure you always do a null check to make sure the data still exists locally, if it doesn't you would need to initiate a server call:
var users = JSON.parse(localStorage.getItem('users'));
if (users != null) {
for (var i = 0; i < users.length; i++) {
alert(users[i].name + " " + users[i].surname);
}
}
You can use sqlite to save the data you already grabbed. So you can decide to grab the whole data again when the user is online or you only grab the new content:
https://developer.android.com/training/basics/data-storage/databases.html
Another possibility is to download your data as .json file and load it in your app. So you'll need the read and write permissions of users.

Session cookies not working in Electron

I'm looking at implementing a login system in an Electron[0] application which I'm building but getting stuck on the part of handling the session. Basically I want to store the users session so it is persisted between application restarts (if "Remember me" is enabled).
I have to make use of an existing back-end which works with cookie authentication and I'm not able to change anything there.
From the Electron documentation on the Session object[1] I gathered that I should be using a partition like f.e. persist:someName in order to have a persistent storage, but this is not persisted between application restarts as it seems.
The way I currently set the cookie is as follows:
// main-process/login.js
const session = require('electron').session;
const currentSession = session.fromPartition('persist:someName').cookies;
currentSession.set({
name: 'myCookie',
url: 'https://www.example.com',
value: 'loggedin=1',
expirationDate: 1531036000
}, function(error) {
console.log('Cookie set');
if (error) {
console.dir(error);
}
});
After running this, I see the Cookie set output, but when restarting the app and running the following code:
// main.js
const session = require('electron').session;
const currentSession = session.fromPartition('persist:someName').cookies;
currentSession.get({}, function(error, cookies) {
console.dir(cookies);
if (error) {
console.dir(error);
}
});
The output returned is [].
Any pointers as to what I'm doing wrong or need to do differently would be highly appreciated!
[0] http://electron.atom.io
[1] http://electron.atom.io/docs/api/session/
An alternative might be to take a look at electron-json-storage. Using this plugin, you can write JSON to a system file throughout the user experience and then recall that file on the application load to replace the user "state".

Best Method to persist data locally in Windows 8 app

I'm creating a Windows 8 App (using HTML 5 and JavaScript) for someone and they've changed up the requirements on me as far as data storage and I could use some guidance. What I need is a data source that will persist only for the local user and not be online in a database or in the cloud. The users will be assigned a tablet with the app installed and they will enter data via forms to customize their local copy.
Here's my requirements:
-Data MUST persist through the lifetime that the app is installed on the device.
-I need to be able to query the data to some degree. I've basically got about 15-20 forms that will accept input data and then a main form that will feed off those 15-20 "sub" forms to populate drop-down and selection options.
-Size should not be an issue, it's all text data and not much of it will be entered. Can't see this going more than a couple hundred MBs over the lifetime of the app.
I've looked into XML, indexedDB (sounds good on the outside, but haven't found any kind of guarantee this will persist), and Application Data (local) which seems extremely limited in my reading capabilities.
What do you think my best bet is? Any advice would be greatly appreciated.
Thanks.
This should help
(function () {
"use strict";
var page = WinJS.UI.Pages.define("/html/index.html", {
ready: function (element, options) {
//do your things
}
});
var roamingFolder = Windows.Storage.ApplicationData.current.roamingFolder;
var afile = "FileToStoreStuff.txt";
function makefile() {
roamingFolder.createFileAsync(afile, Windows.Storage.CreationCollisionOption.replaceExisting)
.then(function (file) {
return Windows.Storage.FileIO.writeTextAsync(file);
})
}
function fileRead() {
roamingFolder.getFileAsync(filename)
.then(function (file) {
return Windows.Storage.FileIO.readTextAsync(file);
}).done(function (text) {
//do stuff
);
}
})();
This kind of assumes that your data may change. If it doesn't you can adapt a different approach, for instance replacing the roamingFolder variable with something like:
var localSettings = applicationData.localSettings;
var localFolder = applicationData.localFolder;
Take a look at the dev docs if you need to access data from within the app elsewhere.

What's the best way use caching data in js on client side?

My application receives data from the another server, using API with limited number of requests. Data changing rarely, but may be necessary even after refresh page.
What's the best solution this problem, using cookie or HTML5
WebStorage?
And may be have other way to solve this task?
As much as cross browser compatibility matters, cookie is the only choice rather than web storage.
But the question really depends on what kind of data you are caching?
For what you are trying, cookie and web-storage might not be needed at all.
Cookies are used to store configuration related information, rather than actual data itself.
Web storage supports persistent data storage, similar to cookies but with a greatly enhanced capacity and no information stored in the HTTP request header. [1]
I would rather say, it would be stupid to cache the entire page as cookie or web-storage both. For these purposes, server-side caching options might be the better way.
Update:
Quoting:
data about user activity in some social networks (fb, vk, google+)
Detect the web-storage features, using libraries like mordernizr and if does not exists fall back to cookie method. A simple example
if (Modernizr.localstorage) {
// browser supports local storage
// Use this method
} else {
// browser doesn't support local storage
// Use Cookie Method
}
[1]: http://en.wikipedia.org/wiki/Web_storage
I wrote this lib to solve the same problem:
Cache your data with Javascript using cacheJS
Here are some basic usages
// just add new cache using array as key
cacheJS.set({blogId:1,type:'view'},'<h1>Blog 1</h1>');
cacheJS.set({blogId:1,type:'json'}, jsonData);
// remove cache using key
cacheJS.removeByKey({blogId:1,type:'json'});
// add cache with ttl and contextual key
cacheJS.set({blogId:2,type:'view'},'<h1>Blog 2</h1>', 3600, {author:'hoangnd'});
cacheJS.set({blogId:3,type:'view'},'<h1>Blog 3</h1>', 3600, {author:'hoangnd'});
// remove cache with con textual key
// cache for blog 2 and 3 will be removed
cacheJS.removeByContext({author:'hoangnd'})
Here is an example of caching data from JQuery AJAX. So if you only want to make the call when you don't have the data yet, its really simple. just do this (example). Here we first check if we have the load information (keyed on line, location and shipdate), and only if we dont, we make the AJAX call and put that data into our cache:
var dict = [];
function checkCachedLoadLine(line, location, shipDate, callback) {
var ret = 0;
if(!((line+location+shipDate) in dict)) {
productionLineService.getProductionLoadLine(line, location, shipDate, callback);
}
return dict[line+location+shipDate];
}
...then in the call back write the value to the cache
function callback(data) {
if (!data) {
document.getElementById('htmlid').innerHTML = 'N/A';
} else {
document.getElementById('htmlid').innerHTML = data[0];
dict[data[2]+data[3]+data[4]] = data[0];
}
}

Categories