I have a jobs website with several different job description pages and with 1 application page with a form.
i.e.
/admin-clark -> /application
/sale-rep -> /application
I would like to pre-populate an input field in the form with the id #jobTitle.
I would like to do the following-
Get the previous URL
Store it in local storage
Sanatize url(remove dashes etc)
Use jQuery to fill in the field with id jobTitle
Or is a there a better way of doing this?
This is what I have so far
var pathname = window.location.path.replace(/^\?$/, '').toUpperCase();
localStorage.setItem("pathname ", pathname );
$('#jobTitle').val(pathname);
in many cases(Not in every case) will get you the URL of the last page if they got to the current page by clicking a link using document.referrer; See here
You can also take help from here
Related
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
So, I understand this is an odd question. I have 2 pages, one that somebody fills out w/ a bunch of inputs. The next page would be a "print to pdf" type deal w/ Coldfusion. However, I want to send all the info to the next page and not lose what the person entering data has put in. Is there a way with jQuery (or some other option in CF that I haven't seen) to potentially grab the $('body') and pass it to sub in on the next page so it keeps the <input> values? I don't want to do a form submit, as there are a bunch of calculations that also take place based off those inputs that are shown, using javascript, and <cfdocument> has trouble with javascript after the fact.
I would serialize all the form input values using jQuery's serializeArray, and store it in the localStorage. In the next page, just read the localStorage and parse your data back to an object using JSON.parse.
Page 1 :
localStorage.formData = $("form").serializeArray()
Page 2 :
var formData = JSON.parse(localStorage.formData)
...aaaand you'll get all your data in an object on page 2.
Ok, so the element data to local storage worked, but the way I actually did it was writing the $('body').html() to a string, passing that using $.ajax() to a cfc file, where I wrote a text file to the CF temp directory using <cffile>, then re-rendered that text into HTML/CFML on the PDF page using <cfinclude>. Hope this helps someone if they need it!
You can cache the data for use on another page in CFML. I do this with Railo, but Adobe CF has a similar function. Any data I want to use on the next page goes in to an array of structs. I haven't tried cacheput('formdata', form), but it seems like it would work.
Page 1
// Empty cache storage
cacheClear();
// call the function to cache data
cachePut('cData', data);
Page 2
// get items from the cache
data = cacheGet('cData');
I'm passing data on a page1 through a querystring onto page2, when a user clicks the button "send" the data is passed on the querystring and page2 gets the 'data=..' parameter from the querystring and shows it's value on the page.
The problem is that the data on page1 is created through the user by the input textbox and can be quite long. This gives us the following error when the user clicks "send"
URL Requested is too long
This is the code used to get the span element(submitted text by user) and convert it to a variable which is added onto the querylink:
$('#send').click(function() {
var data_text = $('span').prop('outerHTML');
window.location.href = 'http://swter.com/send.php?data=' + data_text + '';
return false;
});
Are there anyways around it apart from limiting the amount of chars a user can type?
So you could split the contents of the textarea into multiple strings using String#split and then loop through the resulting array and make AJAX GET requests to your back end server. You will need to include a form of unique identifier that ties each batch of data together on the server, and an index so you can rebuild it, ie:
?id={{unique_id}}&page=1&total=6&body={{message_page_1_of_6}}
However, as pointed out, a POST request would be more appropriate here.
I have an Instant Message feature on my site which uses a popup window. When a user makes an IM post, their picture is added to the post. I am able to save on a database query for each IM post (so the popup does not have to query the database to retrieve the user's picture for each post) by retrieving the stored user pic file name from a form (UserPicStorage...a separate query is not required to grab $sql['picture']...it's already present on each of the main pages when these pages load) on each of 5 non-popup, main pages (one page is an exception, see below) of my site as follows:
<form id="UserPicStorage"><input type="hidden" name="UserPic" value="<?=
$sql['picture'] ?>"></form>
I have an About Us page which does not need a database query to load. So to save a query if a user posts an Instant Message while on the About Us, I pass $sql['picture'] to the a href as follows:
About Us
so the popup can retrieve the userpic if there is an IM post while the user is on About Us.
However, the user can use AJAX on one of the 6 main pages to change his/her user picture.
So I can't use this:
About Us
because if the user changes his/her photo, $sql['picture'] (which was valid on page load)
is no longer the current photo. I did a lot of searching, but could find nothing to support
something like the following method:
About Us
I tried this and simply passed the literal string document.forms.UserPicStorage.UserPic.value. So did the following:
About Us
Is there any way to append the input value of a form directly to the a href?
You should just use
About Us
(well, probably you should encode $sql['picture'])
And when you make the AJAX request, update it as a success callback:
ajax.onreadystatechange = function() {
if (ajax.readyState===4 && ajax.status >= 200 && ajax.status < 300) {
/* AJAX successful */
myAnchor.src = "about.php?userpic=" + encodeURIComponent(
document.forms.UserPicStorage.elements.UserPic.value
);
}
};
I am actually using css and html and js.
I have 6 category pages (e.g category1, category2, category3, ...) that point to the same page (e.g. fixed) and that pages points to other 3 pages (e.g. Endpage1, Endpage2, Endpage3).
I've added a nav bar to help user don't get lost on the website.
The Navbar is structured like:
Category > fixpage > Endpage
e.g.)[(Category1 >>> fixpage >>> Endpage3]
when I am in category page it just show
category1 >>>
when I click to link I go on fixpage and the navbar show
<a href="#"> category1 <a> >>> Fixpage
I manage (thanks to a user here on stackoverflow) to do a function that pass the starting page with get method ?page=category1 in the link and then it write it on the navbar of the Fixpage
with this function http://fiddle.jshell.net/KFmG8/1/
Now the problem is that when I am on Endpage it shows
undefined >>> Fixpage >>> Endpage1
and when from Endpage i want to go back to Fixpage, the variable is lost too so it shows
undefined >>> Fixpage
can I do something or is better switch to cookies/session?
You could pass a more complex value as the page query parameter to handle the series of parent pages.
?page=category1/Fixpage
Here is something along the lines of what I mean pulling out some of the code from your fiddle link. qs.page is setup to read like a URL path and then the buildPageStr function will build out the display inside the link HTML.
function fillLink()
{
qs = getQueryParams(document.location.search);
alert(qs.page);
var pageStr = buildPageStr(qs.page);
document.getElementById("backLink").href="c:/sito2/risorse/prove/" + qs.page;
document.getElementById("backLink").innerHTML = pageStr;
}
//Removes the '/' and places ' >>> ' between each page name
function buildPageStr(tokens) {
if(tokens) {
return tokens.split(/\//).join(' >>> ');
}
return "";
}
Just to answer your title question, there is no way to store values IN JavaScript over multiple pages. The JS context gets cleared and rebuilt on each page view. So it seems you are actually asking a more practical question of how to maintain state, or even simpler, how to manage breadcrumbs over multiple pages without server-side session data.
Since you are already pulling one page out of the query string, it shouldn't be much more difficult to build the entire breadcrumb in the query string.
So something like:
?pages=Startpage.Fixpage.Endpage
Would give you the full breadcrumb path in the URL. Then instead of displaying the value directly you split it back into pages
var pages = qs.page.split('.');
You can, of course, use cookies instead but you'd have the same problem really. You need to manage your entire list of breadcrumbs as the user navigates from page to page. And it's easy enough to just do that by "serializing" the array of pages into a string and then splitting it back up on the other side. Using the query string has the added benefit of producing the same breadcrumbs based on the URL regardless of the state of the user's cookies.