Pass div and value from one page to another - javascript

I have assigned an id of the user's name to each div generated by loop. This is fine. Each div/button has the username as its identity. However, using the examples here Load content of a div on another page and in other posts I am trying to send that div and its contents to another page and also pass the name value with it. My attempt is not working although the alert is alerting the name. Am I correctly passing the value? How can I recreate the div on the next page? Finally, is this even the correct approach because eventually I want to attach a table to the person. Long-winded enough?
identity = results.rows.item(i).username;
userDiv.id = identity;
console.log(identity);
(function (identity) {
userDiv.addEventListener("click",
function () {
window.open("whatever.html");
$('#singleUser').load('index.html #userDiv');
//var singleUser = document.getElementById("singleUser");
//singleUser.appendChild(userDiv);
alert(identity);
console.log(identity);
}, false);
})(identity);

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

Can we use document.getElementById() dynamically

I am trying to print an html page using window.print. Where as the html page is getting updated for each rest API call. so can i print continuously for each rest API call???
var myPrintContent = document.getElementById("data-box");
var myPrintWindow = window.open('','Print-Window');
var popupWindow = window.open('','Print-Window');
popupWindow.document.write('<TITLE></TITLE>\n');
popupWindow.document.write('<URL></URL>\n');
popupWindow.document.write('<script>\n');
popupWindow.document.write('function print_win(){\n');
popupWindow.document.write('\nwindow.print();\n');
popupWindow.document.write('}\n');
popupWindow.document.write('<\/script>\n');
popupWindow.document.write('</HEAD>\n');
popupWindow.document.write('<BODY onload="print_win()" >\n');
popupWindow.document.write(myPrintContent.innerHTML)
popupWindow.document.write('</BODY>\n');
popupWindow.document.write('</HTML>\n');
popupWindow.document.close();
This is what i am doing. so content of data-box.innerhtml is different for different employees. So on each time i call print one page i will get. But for the next employee if i am again calling the print function the called employee details is only getting printed. So what i want is if i gave different id s for different employees, how can i get all the ids dynamically. so that once i call print i can get all the data s of all employee printed.
window.print();
as can be read atw3school is a method to print the current window. It has nothing to with document.getElementById() method.
If your are interested in printing your page, simple print the window. That's it.
But if you want to use document.getElementById() for some other purposes, you can pass variable (the dynamic id) of element in consideration.
here is how you do it
var myId = "my-element-id";
var myContent = document.getElementById(myId).innerHTML;
Better post any code for better help.

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. :)

Loading div object from DoM. Convert to Text File. Then reload div object back when page is reloaded

I have a co worker who asked me for help but I wasn't able to. Essentially he has created a page with pure java script that has a div element and child div elements. Each one of those child div elements have a form. He wants to be able to save all that hierarchical data in a text file whether or not it is in json / html in which he can load it later on without having to process it manually again. That way the next time the person loads the page, they are greeted with all the same information and div elements.
So essentially when you load the page again, you are able to simply dump the json / html into the DoM and it will automagically work. He's been on it for 2 days now, I thought I would ask you guys for some help or at least lead me on the right path.
Doing so would take three steps:
Get all the form data values from the DOM (a simple matter of knowing how to access HTML forms and putting them into an object)
Save the form data object into localStorage or on server (saving on the server would only work if you save some identifying information about the user, like if they are logged in, or their IP address)
On form load, check for saved data (on localStorage or server) and load it into the forms.
You can get the data of all forms into a JSON object like so:
function getAllFormsData(){
var formsData = {}
for(var i=0;i<document.forms.length;i++){
var form = document.forms[i],
name = document.forms[i].name;
formsData[name] = {}
for(var j=0;j<form.elements.length;j++){
var element = form.elements[j];
if(element.type=="submit") continue;
formsData[name][element.name] = element.value;
}
}
return formsData;
}
so formsData is a JSON object that contains properties for each form (by its name, but you can use ID if you prefer) on the page, and the value of each of those properties is an object containing the name and value of each input element (unless it's a submit type element).
Saving the data can be triggered either by the user clicking a "Save" Button on the page, or by using the window.onunload event. (If you are using localStorage, you can also set the saving function inside a setInterval that triggers every 30 seconds or whatever.)
localStorage is pretty straightforward (with a really easy API), but only allows string values. If you want to load a whole object into it instead of having to loop through and save each value, you can use a library. I have found store.js to be very useful and straightforward, and it serializes data for you so you don't need to mess with JSON.parse or JSON.stringify.
So, using the library, the save function would boil down to something as simple as:
function saveAllFormsData(){
var data = getAllFormsData();
for(var formName in data)
store.set(formName, data[formName]);
}
And on load, you can call this function:
function restoreAllFormsData(){
var forms = document.forms;
for(var i=0;i<forms.length;i++){
var form = forms[i];
if(store.get(form.name)){
for(var j=0;j<form.elements.length;j++){
var element = form.elements[j];
if(element.type=="submit")
continue;
element.value = store.get(form.name)[element.name];
}
}
}
}
I suggest looking into HTML5 local storage. This will allow you to save form data on the client, which can be used for repopulation when necessary.
Alternatively, you could also set a cookie on the client. However, this method has drawbacks that are discussed in the aforementioned document.
Either approach will likely require you to stringify any HTML before storage, due to the key:value nature of these data storage methods.

How can I bind own data to the history object using JQuery Mobile?

I'm looking for a nice way to bind my own app data (like currentQuestion, currentAnswer) to the history object.
I tried to keep track in the hashchange event, but that gets complicated.
I try it with url parameters, but I want to have status object with some entries for each element on the history stack, so I would have to have many parameters.
Is there a way just to add an object to the history stack?
If you use jquery mobile ajax transition you will have access to the same global jquery object on all pages, you can append data to it, for example in the first page you assign currentQuestion and currentAnswer
$.currentQuestion = 'something';
$.currentAnswer = 'something';
On the next page you can access these variables easily
console.log($.currentQuestion);
That is how I move data between pages inside jquery mobile
I found the way. You can just insert variables into the history stack:
var urlh = $.mobile.urlHistory;
if( "factId" in urlh.stack[urlh.activeIndex] ) {
// load
cp10.score.currentFactId = urlh.stack[urlh.activeIndex].factId;
} else {
// store fact id in history object
urlh.stack[urlh.activeIndex].factId = cp10.score.currentFactId;
}
Here I insert a variable 'factId'. If it is not already in the stack element (what happens when the page is first loaded), then insert it. Later (when hte user hits the back button or so) you can retrieve it from there.

Categories

Resources