Sharing data between web pages with JavaScript - javascript

I'm working on a GPS/mapping app using Node.js, express, Socket.IO, and MongoDB.
The tracker page uses HTML5 geolocation and Socket.IO to send coords to the server and store them into MongoDB.
I'm now working on creating user pages so a user can view previously recorded data. I'm currently minus a log in page, so index.html just populates a list of user names and I can select one.
My problem is that I am unsure of how to best pass data such as the username of the selected user to the next page. I have been trying to avoid opening a socket connection to the server just to pass one username but if that is the best way then no problem. I am also aware of localStorage as an option.
Here is some code snippets to give you an idea of what I'm working on:
index.html:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
$.ajax({
dataType: "json",
url: "/getusers"
}).done(function(data) {
console.log("--->", data);
for(var i=1; i<data.length; i++) {
$('#list').append("<li><a href=http://localhost:3000/mapPage.html>" + data[i].name + "</a></li>");
}
$("a").click(function(e) {
alert("--->", $(this).html());
//alert("--->", $(e).html());
//alert("--->", $(e).getVal());
//window.localStorage.setItem("username", )
});
});
});
</script>
</head>
<body>
<ul id='list'>
</ul>
</body>
</html>
The ajax is just hitting an express route that asks the MongoDB for collection names (each user has a collection). Also I'm having trouble getting the data from the specific anchor tag I clicked on. So I need to get the user name I clicked on and send it to the "userpage", which, for now would be almost identical to index.html, it would select the specific user collection and show a list of available objects (arrays of map coords);
tl;dr: get data from anchor tag clicked, make data available to next page.

That's exactly what sessionStorage were designed for - to pass data from one page to another. localStorage can also be used for that but it is more for persistence of some data between sessions.

If you have to pass data like that between pages the simplest way that comes to my mind is just passing it as a query string.
http://localhost:3000/userPage.html?username=jim&user=jdawg149
Then you can read those out into variables on the destination page.
You can get and set the query string pretty simple with some simple methods on the window as discussed here:
http://css-tricks.com/snippets/javascript/get-url-and-url-parts-in-javascript/
You can also get a little more complex with it by using a function with RegEx to parse the URL, as answered here:
How can I get query string values in JavaScript?
Keep in mind that you should limit your URLs to ~2000 characters.

Related

How to create a sharable url containing dynamic html (javascript)

What is the best practice to create unique shareable urls for some text lists users create?
It's a single page website with a content div where users create text lists. Once they click share, how can I store those values inside a shareable url so that another user going to that address loads the same list?
I'm using html, js, jquery, php.
EDIT: as suggested below i'm already saving the lists on a database (firebase), and each have an unique ID, so I'd need to understand how I can create urls with a list id in it, and how to read the url back.
EDIT 2: so this is the code i'm using right now, combining answers from marzelin and the Alchemist Shahed in my other question about my database structure (Firebase how to find child knowing its id but not its parent's id (js)):
//js inside window load function:
const keyOfDynamicHtmlItemRef = new URL(window.location).searchParams.get("share")
if (keyOfDynamicHtmlItemRef) {
var dynamicHtmlListRef = firebase.database().ref('users');
// var dynamicHtmlItemRef = dynamicHtmlListRef.child(keyOfDynamicHtmlItemRef);
// console.log(keyOfDynamicHtmlItemRef);
// dynamicHtmlItemRef.once("value").then(dynamicHtmlSnap => {
// texta.innerHTML = dynamicHtmlSnap.val();
// });
dynamicHtmlListRef.once('value').then((snapshot)=>{
snapshot.forEach(function(data) {
if (data.key == keyOfDynamicHtmlItemRef) {
myVar = data.c;
myContentDiv.innerHTML = myVar;
}
});
});
}
and i'm simply trying to manually write the url in the searchbar as a first step, as https://example.com/?share=<random list id i copied from db>, but it does nothing.
So the way I would to this is I would have the users share click trigger a save to database saving all the dynamically generated content into a table.
One of the table values would be a randomly generated unique identifier of some sort that I would use as a query in the url like https://www.example.org/?share=skd822475
Then when a user visits the site and that query is in the url id use the unique identifier to look up the database and publish the dynamic content back on the page.
I would also put a half life on the database entry's of say no more than 30 days so that it doesn't clog up the db.
Saving data and creating shareable link:
document.querySelector(".share").addEventListener("click" => {
var dynamicHtmlListRef = firebase.database().ref('dynamic_html');
var dynamicHtmlItemRef = dynamicHtmlListRef.push();
dynamicHtmlItemRef.set(userCreatedDynamicHtml);
var keyOfDynamicHtmlItem = dynamicHtmlItemRef.key;
var linkToDynamicHtmlItem = `${window.location}?share=${keyofDynamicHtmlItem}`;
alert(`link: ${linkToDynamicHtmlItem}`)
})
Showing the dynamic HTML based on query parameters:
const keyOfDynamicHtmlItemRef = new URL(window.location).searchParams.get("share")
if (keyOfDynamicHtmlItemRef) {
var dynamicHtmlListRef = firebase.database().ref('dynamic_html');
var dynamicHtmlItemRef = dynamicHtmlListRef.child(keyOfDynamicHtmlItemRef);
keyOfDynamicHtmlItemRef.once("value").then(dynamicHtmlSnap => {
document.querySelector(".dynamic-html-mountpoint").innerHTML = dynamicHtmlSnap.val();
});
}
Let's start with the first question "How to create urls with a list id in it?"
The thing is that to answer this one we need to answer the second question first witch is
"How to read the url back?"
Consider that you have a php page named "draft". when a user visit https://www.example.com/draft?listId=an_id you will get listId using php like so $_GET("listId") and use that value to retrieve the list data and display the page content.
Now coming back to the first question, if the user share the draft like in social media (ex: facebook) then there is no problem because he will share a link and all his followers and any other user can access it easily. but if the user just save the draft then you will have to change the page url dynamically like this window.history.pushState(null, null, '/draft?listId=your_newly_created_id'); and so the user will copy the url and do whatever he wnt with it (sharing it in stackoverflow maybe example using jsfiddle http://jsfiddle.net/F2es9/ (you can change the url to look like this using 'htaccess' file)) at the end I would like to tell you that we don't "create" urls.
Edit
without using php code (or any other server side code). the difference will be in retrieving the data.
instead of using $_GET("listId") you will use new URL(window.location).searchParams.get("listId") to get the list id in javascript then using this value you can retrieve data from firebase and display your content

Attempting to use a global array inside of a JS file shared between 2 HTML files and failing

So I have one HTML page which consists of a bunch of form elements for the user to fill out. I push all the selections that the user makes into one global variable, allTheData[] inside my only Javascript file.
Then I have a 2nd HTML page which loads in after a user clicks a button. This HTML page is supposed to take some of the data inside the allTheData array and display it. I am calling the function to display allTheData by using:
window.onload = function () {
if (window.location.href.indexOf('Two') > -1) {
carousel();
}
}
function carousel() {
console.log("oh");
alert(allTheData.toString());
}
However, I am finding that nothing gets displayed in my 2nd HTML page and the allTheData array appears to be empty despite it getting it filled out previously in the 1st HTML page. I am pretty confident that I am correctly pushing data into the allTheData array because when I use alert(allTheData.toString()) while i'm still inside my 1st HTML page, all the data gets displayed.
I think there's something happening during my transition from the 1st to 2nd HTML page that causes the allTheData array to empty or something but I am not sure what it is. Please help a newbie out!
Web Storage: This sounds like a job for the window.sessionStorage object, which along with its cousin window.localStorage allows data-as-strings to be saved in the users browser for use across pages on the same domain.
However, keep in mind that they are both Cookie-like features and therefore their effectiveness depends on the user's Cookie preference for each domain.
A simple condition will determine if the web storage option is available, like so...
if (window.sessionStorage) {
// continue with app ...
} else {
// inform user about web storage
// and ask them to accept Cookies
// before reloading the page (or whatever)
}
Saving to and retrieving from web storage requires conversion to-and-from String data types, usually via JSON methods like so...
// save to...
var array = ['item0', 'item1', 2, 3, 'IV'];
sessionStorage.myApp = JSON.stringify(array);
// retrieve from...
var array = JSON.parse(sessionStorage.myApp);
There are more specific methods available than these. Further details and compatibility tables etc in Using the Web Storage API # MDN.
Hope that helps. :)

get jquery.data() related to an element from a saved html using javascript or jquery

I have some html that I want to save in database for a later retrieve.
Let's imagine the html is a simple div
<div id="mydiv">This is my div</div>
I use jQuery.data() to store some information related to that div like this :
$("#mydiv").data("divNumber", "5").data("divRole", "adminMessage") .....
Then finally I save the html in database, but I would like to be able to get those information later when I need them :
var myHtml = { here I get the html from my database }
$("body").append(myHtml);
console.log( $("#mydiv").data("divNumber") ); // I want it to show 5
console.log( $("#mydiv").data("divRole") ); // I want it to show adminMessag
from my understanding of jquery.data() I think it will just store those data information temporary in an internal cache and if I save the html in the database, and I leave the page, they will be lost !!
So is there a way to keep those jquery.data() information and retrieve them whenever I want ? or maybe there is another "better" way to achieve the same thing (I am not looking for localStorage method)
You can convert the .data() to data attributes on the html and save that.
$("#mydiv").data("divNumber", "5").data("divRole", "adminMessage");
$.each($("#mydiv").data(), function(k,v){
$("#mydiv").attr("data-"+k.replace(/[A-Z]/g, "-$&"), v);
});
var toDatabase = $("#mydiv")[0].outerHTML;
//save to database
// ...
// retrieve from database
var fromDatabase = $(toDatabase);
$('body').append(fromDatabase.data('divNumber'));
$('body').append('<br>');
$('body').append(fromDatabase.data('divRole'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mydiv">This is my div</div>
If you want to have a database in the browser which works across all platforms consistently, despite each browser having different underlying storage mechanisms try PouchDB. It is great! You can keep it just in your browser session which will persist until the user clears their data OR you can have it persist to a CouchDB database server.
http://pouchdb.com/
There are many good CouchDB providers if you dont want to setup your own although that is simple to do. IBM Cloudant is free until your usage is above $50 per month:
https://cloudant.com/
It is very simple to use, see here. A couple lines of code to create a db object and a few to put / fetch. Then one line each to setup a remote copy and one line to live sync to it.

Change URL data on page load

Hello I have a small website where data is passed between pages over URL.
My question is can someone break into it and make it pass the same data always?
For example let say, when you click button one, page below is loaded.
example.com?clicked=5
Then at that page I take value 5 and get some more data from user through a form. Then pass all the data to a third page. In this page data is entered to a database. While I observe collected data I saw some unusual combinations of records. How can I verify this?
yes. as javascript is open on the website, everyone can hack it.
you will need to write some code on you backend to validade it.
always think that you user/costumer will try to hack you sytem.
so take precautions like, check if user is the user of the session, if he is logged, if he can do what he is trying to do. check if the record that he is trying get exists.
if u are using a stand alone site, that u made the entire code from the ashes, you will need to implement this things by yourself.
like using the standard php session, making the data validation etc.
or you can find some classes that other people have made, you can find a lot o this on google. as it is a common problem of web programing.
if u are using a backed framework that isnt from another world, probably already has one. sp, go check its documentation.
html:
<a id = 'button-one' name = '5'> Button One </a>
javascript:
window.onload = function() {
document.getElementById('button-one').onclick = function() {
changeURL(this.attributes.name.value);
};
};
function changeURL(data) {
location.hash = data;
}

creating a configuration page and passing variables to a simply.js app

i developed a simply.js app that fetches bus arrival time from a webservice, problem is that as of now it work only for one stop.
i want to create a configuration page with a multiselect where i could choose multiple stops , sending them to the pebble as an array and at the press of up/down buttons i want to cycle the array to show different bus stops.
Im not good in C, i prefere javascript thats because i used simply.js.
id like to know and learn how to do it, because i think online there isnt much documentation and examples.
Found a similar question/ issue at simply.js github page https://github.com/Meiguro/simplyjs/issues/11. The code example below comes from Meiguros first answer. The code sends the user to your configuration website, which you should configure to send json back.
You can probably copy the code example for enabling the configuration window and paste it in the begining of your main pebble app.js file. Do not forget to add "capabilities": [ "configurable" ], in your appinfo.json file. If you are using cloudpebble you should go to the settings page of your app and make sure the configurable box is checked.
var initialized = false;
Pebble.addEventListener("ready", function() {
console.log("ready called!");
initialized = true;
});
Pebble.addEventListener("showConfiguration", function() {
console.log("showing configuration");
//change this url to yours
Pebble.openURL('http://assets.getpebble.com.s3-website-us-east-1.amazonaws.com/pebble-js/configurable.html');
});
Pebble.addEventListener("webviewclosed", function(e) {
console.log("configuration closed");
// webview closed
var options = JSON.parse(decodeURIComponent(e.response));
console.log("Options = " + JSON.stringify(options));
});
(https:// github.com/pebble-hacks/js-configure-demo/blob/master/src/js/pebble-js-app.js - remove space after https://)
To then push the settings back to the pebble i think you need to add
Pebble.sendAppMessage(options);
just before
console.log("configuration closed");
// webview closed
I found this out at the last post on this pebble forum thread http://forums.getpebble.com/discussion/12854/appmessage-inbox-handlers-not-getting-triggered-by-javascript-configuration-data
You can aslo find a configuration website example named configurable.html in the same git as the code example at https:// github.com/pebble-hacks/js-configure-demo remove space after https://
Hope this helps a bit on the way to achieving your goal
So the configuration page is a web page, and you can host it and provide your URL as mentioned by Ankan above.
Like this:
Pebble.openURL('http://assets.getpebble.com.s3-website-us-east-1.amazonaws.com/pebble-js/configurable.html');
Lets say you decide to take the name and age of the user in the configuration page, you would have two text fields for them to enter their information, then you would have a submit button. For the submit button write a javascript function which uses jQuery to take the values of the text fields onclick, then save those values to a variable, and use JSON to send them to the phone. Here is an example of a fully created configuration web page: https://github.com/pebble-hacks/js-configure-demo
Enjoy.

Categories

Resources