How to create a sharable url containing dynamic html (javascript) - 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

Related

Find document by value without its reference

This is a database structure for my image uploading app. The first collection group is ID of the user, its childs are images, with IDs as titles.
I am trying to create a get route for example: domain.com/i/IMAGE_ID, then get that ID and provide image across the page.
Is it possible to find needed document without having the title of its parent?
Is it possible to find needed document without having the title of its parent?
Yes it is possible using a query which is related to a property. Let's assume your know the file name, then please use the following lines of code:
var uidRef = firebase.database().ref("images").ref(uid);
var query = uidRef.orderByChild("fileName").equalTo("Colour7.jpg")
In which the uid is the id of the authenticated user. The result of the query will be the second item in your images node.
Edit:
If you only have the image ID, please use the following lines of code:
var uidRef = firebase.database().ref("images").ref(uid);
var query = uidRef.orderByChild("ID").equalTo("2sj2yAJN3MC24GwjLtDkt")

How to save String value and print it on another page using Google Chrome storage API

I am looking to take user input in and then saving that user input using the google chrome storage api but I cannot find any useful reasources on this topic.
I have 2 elements that I would wish to save permanently using JS:
var title = encodeURIComponent(document.getElementById('title').value);
var url = encodeURIComponent(document.getElementById('url').value);
I want to create an 2 arrays, one that holds the title values and one that holds the url values, then I want to print those values out on another page.
You can use chrome.storage.local object to accomplish that.
If you need to store data in the chrome storage use the following sentence:
chrome.storage.local.set({'titles': [title]});
chrome.storage.local.set({'urls': [url]});
Now, if you want to retrieve the current data in the chrome storage use the following:
let newTile = "new title";
chrome.storage.local.get('titles', function(titles){
titles.push(newTile);
chrome.storage.local.set({'titles': titles});
});
let newUrl = "http://.....";
chrome.storage.local.get('urls', function(urls){
urls.push(newUrl);
chrome.storage.local.set({'urls': urls});
});
Important: What is missing here, are the conditions to check current data in the local storage.
Hope this helps!

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 do I retrieve a JSON of all WooCommerce data on any Wordpress page?

I want to set up a WooCommerce shop for a WordPress site (which I've never done before by the way).
However, I do not want to use any type of WooCommerce generated pages.
What I want is to add/remove products (along with all other relevant product data), create categories, subcategories etc.. using the WooCommerce "control panel" from inside the Wordpress Dashboard and every time I do that, I want a WooCommerce object (containing all that data) to be updated/generated and made available across all (or some specific) pages.
The reason for that is because I want to build everything myself (product pages, cart page, checkout page, category pages, subcategory pages).
In order to populate these pages with the relevant data, however, I'll need to have access to the whole of WooCommerce data from any of those pages.
Some examples will explain better what I'm trying to achieve. (note : I'll be using Javascript and generating everything on the client)
Case #1
Let's say I am in the "Shop" page, and I want to populate a column with all available product categories. I need to be able to do something like that :
var wooCommerceShopData = getAllWooCommerceShopData(); // an Ajax request that will fetch me all that data
var arrayOfAllAvailableCategories = wooCommerceShopData.categories;
Case #2
Now suppose I am in the "sportswear" category. I need to be able to do something like that :
var wooCommerceShopData = getAllWooCommerceShopData();
var productsObjectForCurrentCategory = wooCommerceShopData.categories["sportswear"].products;
Case #3
If I am on a "sportwear"-category product page, I need to be able to do something like that :
var wooCommerceShopData = getAllWooCommerceShopData();
var currentProductData = wooCommerceShopData.categories["sportswear"].products["BLK123XMENSHORTS"];
var currentProductPrice = currentProductData.price;
// etc......
Is this possible and is there an WooCommerce/Wordpress API for that ?
WooCommerce provides a Rest API.
You can find the documentation here:
https://woocommerce.github.io/woocommerce-rest-api-docs/
Hope it helps.
this is probably the best REST API DOCUMENTATION for Woocommerce.

Categories

Resources