I feel there is something fundamental missing here.
This is a node app and the getData is an AJAX database call that gets info about a blog post.
I can load the pages just fine, it simply splits the URL string and uses the right-hand side as the postid, then the post id is sent via getData. That part works but I noticed that if I hit the page twice, and hit back it won't load the old page, it just changes the URL in the address bar, but doesn't actually load the page again.
So if say I put http://localhost:3000/post/&2 it will load the post with the id of 2. I then put http://localhost:3000/post/&3 it will load post with the id of 3. Now from there, if I hit back button, I will have the URL in the bar go back to http://localhost:3000/post/&2 but it will retain the data of http://localhost:3000/post/&3
My current idea, is that the back button does not actually treat them as separate URL's for some reason, so it loads the cache it has from http://localhost:3000/post/&3 because http://localhost:3000/post/&2 and http://localhost:3000/post/&3 are the same to it.
<html>
<head>
<link rel="stylesheet" type="text/css" href="../css">
</head>
<body onLoad="buildPage()">
<div id='container'>
<div id='head'>header icons</div>
<div id='body'>
<div id='sidebar'>sidebar
<div id='sidebarLinks'></div>
<div id='sidebarAdSpace'></div>
</div>
<div id='mainpage'>mainpage</div>
</div>
</div>
<script src='../public/grabdata.js'>
</script>
<script>
function buildPage() {
var page=3;
var url= window.location.href.split('&');
var page=url[1];
//alert(param);
getData(page, function(str) {
str = JSON.parse(str);
var linkHTML = '';
var postHTML = '';
linkHTML += "<ul>";
for (var i in str) {
linkHTML += "<li><a href='../post/&" + str[i].id + "'>" + str[i].title + "<i>~" + str[i].published.slice(0, 10) + "</i></a></li>";
}
linkHTML += "</ul>";
postHTML+="<div class='poster'><div class='posterHead'><div class='postTitle'>"+str[0].title+"</div><div class='postSeries'>Part of the "+str[0].series+" series</div></div><div class='postBody'>"+str[0].body+"</div><div class='postAuther'>"+str[0].auther+"</div><div class='postPublished'>"+str[0].published+"</div></div>";
document.getElementById('sidebarLinks').innerHTML = linkHTML;
document.getElementById('mainpage').innerHTML = postHTML;
})
}
</script>
</body>
</html>
well, in case anyone else finds the question useful
i solved my own problem
i misunderstood how the history cache works. it never unloaded the data because it does not recognize a paramater change as a new page.
i solved my issue using pushState and altering the state inside the history itself.
thanks for trying though guys and gals.
Related
(1)
My example Current URL along with Parameters is ----
www.example.com?fname=John&femail=john123#example.com
(2)
Through html / JavaScript
I want to check Current URL Parameter whether it contains any data in
fname
(3a)
Next, If there is No URL Parameter present then Redirect to "www.example.com/error-page"
or
(3b)
If the parameter fname have some data (No need for any Validation of data) meaning the parameter fname is not empty then should Continue with the execution of Current Page.
I tried the following successfully :
<!doctype html>
<html>
<head>
<body>
<div>
<p id ="dd"></p>
</div>
<meta charset="UTF-8"/>
<script type="text/javascript">
var iid=document.getElementById("dd");
var getURL=window.location.href;
var theString = window.location.href;
var theWord = "fname";
var theWordExp = /fname/g;
if (theString.search(theWordExp) == -1) { window.location.href=
('www.example.com/error-page'); };
</script>
</body>
</head>
</html>
Explanation:
"I want to check Current URL Parameter whether it contains any data in fname"
The getQueryParam function is explained here
How to get "GET" request parameters in JavaScript?
basically it's almost the same as your approach using the location href to parse the params
"If there is No URL Parameter present then Redirect to" else continue, for this you'll only need to wrap it inside a div, if the conditional is false (found param) then it'll just not run the statement inside if block (the one that will redirect user to error page)
Note that you have many other option to implement, check with the compatibility of browser, behaviour of redirection can also be changed to replace the last history page so user cannot go back to the previous URL that throw the error using window.location.replace method
const getQueryParam = (name) => {
if (name = (new RegExp('[?&]' + encodeURIComponent(name) + '=([^&]*)')).exec(location.search))
return decodeURIComponent(name[1]);
}
let fnameParam = getQueryParam("fname");
if (!fnameParam) {
window.location = "http://www.example.com/error-page";
};
<!doctype html>
<html>
<head>
<body>
<div>
<p id="dd"></p>
</div>
</body>
</head>
</html>
I currently have a sitation where I can click on an image and it will return a new image, and in the previous grid-item, it will return the day and time I clicked it.
What I want is to have this BUT where I also can see the updated image and clicked time after closing and re-opening the browser. - What is the easiest / quickest way to achieve this?
I feel like adding to my database would be a way forward, but if that is what I would need to do, how would I go about storing and out-putting the time based on the time I click?
(This is not intended to be a live site, or for others to see or use, so local quick-fixes are viable).
foreach ($flavours as $key => $flavour) {
echo "<div class='grid-container'>";
echo "<div class='item7'><p id='p3'>Sylus: </p></div>";
echo "<div class='item8'><img src='htts://i.i.com/k.jpg' onclick='cS(this)' /></div>";
echo "</div>";
}
function cS(element) {
if (element.src == "htts://i.i.com/k.jpg")
{
element.src = "http://i.i.com/v.jpg";
var d = moment().format('dddd HH:mm');
element.parentElement.previousElementSibling.firstChild.innerHTML = "Sylus: " + d;
}
else
{
element.src = "htts://i.i.com/k.jpg";
element.parentElement.previousElementSibling.firstChild.innerHTML = "Sylus: ";
}
}
Try this example using localStorage. This will find the <p> tag elements within the body, and then uses each element to get the id for reference.
I tried using a fiddle here, but the site has a security complaint with the localStorage.
Copy/paste this code to a file to give it a try. Note that you will likely need to update the moment.js reference in this code to match your file path.
<!doctype html>
<html>
<head>
<title>localStorage example</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="moment.js"></script>
</head>
<body>
<div class='grid-container'>
<div class='item7'><p id='p0'>Sylus: </p></div>
<div class='item8'><img src='htts://i.i.com/k.jpg' onclick='cS(this)' /></div>
</div>
<div class='grid-container'>
<div class='item7'><p id='p1'>Sylus: </p></div>
<div class='item8'><img src='htts://i.i.com/k.jpg' onclick='cS(this)' /></div>
</div>
<script>
function cS(element) {
var pTag = element.parentElement.previousElementSibling.firstChild;
if (element.src == "htts://i.i.com/k.jpg")
{
element.src = "http://i.i.com/v.jpg";
var d = moment().format('dddd HH:mm');
var pText = 'Sylus: ' + d;
pTag.innertHTML = pText;
// Set (save) a reference to browser localStorage
localStorage.setItem(pTag.id, pText);
}
else
{
element.src = "htts://i.i.com/k.jpg";
pTag.innerHTML = "Sylus: ";
// Remove the stored reference. (delete this if not needed)
localStorage.removeItem(pTag.id);
}
}
$(document).ready(function() {
pElements = $('body').find('p').each(function(index, element) {
// Get the localStorage items. The retrieved <p> elements,
// we use their id value to reference the key in storage.
storageItem = localStorage.getItem(element.id);
if (storageItem) {
$('#' + element.id).text(storageItem);
}
});
});
</script>
</body>
</html>
After clicking an image (will need to replace with something real), open the browser's web inspector interface, click the Storage tab, and then expand the Local Storage in the list (see image below), and choose the file being tested.
There will be key/value pairs displayed. The keys are references to the <p> tag id's, and the value will have a label-date strings such as Sylus: Wednesday 22:28.
Once you see an entry, or two, being set to the storage, close and then reopen the browser tab. The <p> elements that had dates should be reloaded with their values from the storage.
The browser's Local Storage area should be similar to the image below:
save it to local storage, or a cookie with the exp. date too far in the future
In a.html:
I have a textarea that is converted into a link after the user clicks the submit button. When the user clicks on the link they are redirected to b.html.
<textarea id="sentenceId">
</textarea>
<br>
<button type="button" id="buttonId" onclick="createLink(document.getElementById('sentenceId').value)">Submit
</button>
<p id="demo">
<a id ="link" href="b.html"></a>
</p>
In b.html:
I would like to display the original text.
In script.js:
function createLink(val) {
document.getElementById("link").innerHTML = val;
document.getElementById('buttonId').style.display = 'none';
document.getElementById('sentenceId').style.display = 'none';
}
If you want to open a new page and get the text there, you could use a post-form and an input[type="hidden"] to send the text and display it afterwards.
If you wand the link to be sendable, you'd either have to encode the text as get-parameter or save it to a database and add the id of the entry to the link.
As #Kramb already mentioned, localStorage is a possibility, but only if you stay on the same browser and both pages have the same domain.
Using localStorage
The localStorage property allows you to access a local Storage object. localStorage is similar to sessionStorage. The only difference is that, while data stored in localStorage has no expiration time, data stored in sessionStorage gets cleared when the browsing session ends—that is, when the browser is closed.
a.html
function createLink(val) {
document.getElementById("link").innerHTML = val;
document.getElementById('buttonId').style.display = 'none';
document.getElementById('sentenceId').style.display = 'none';
localStorage.setItem("textArea", val);
}
b.html
function getText(){
var textVal = localStorage.getItem("textArea");
}
Another option would be to use a query string.
a.html
function navigateTo(val){
window.href.location = "b.html?text=" + val;
}
This will pass the value of the text from textarea with the url during navigation. Once b.html has loaded, you can do the following.
b.html
function getText(){
var url = window.location.href;
var queryIndex = url.indexOf("=") + 1;
var passedText = url.substring(queryIndex);
document.getElementById('foo').value = passedText;
}
This is possible using JavaScript. You can do an AJAX call to another page on you website, and search for an element to get its content. In you're case an textarea
I wrote an example on codepen.io for you. Click here
To make things simpler im using jQuery in this example.
So how does it work?
First of, include jQuery inside the <head> tag of you're website.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
I created the following structure
structure
root
scripts
jQuery.min.js
index.js
index.html
textarea.html
Contents of index.html
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Meta -->
<meta charset="UTF-8" />
<title>My New Pen!</title>
<script type="text/javascript" src="scripts/jquery.min.js"></script>
<!-- Styles -->
<link rel="stylesheet" href="styles/index.processed.css">
</head>
<body>
<button id="clickme">To load the textarea content, click me!</button>
<div id="content">The data from the textarea will be shown here, afte you click on the button :)</div>
<!-- Scripts -->
<script src="scripts/index.js"></script>
</body>
</html>
Contents of texarea.html
<textarea id="textarea">
I am the content of the textarea inside the textarea.html file.
</textarea>
Contents of index.js
(function() {
$(document).ready(function() {
/**
* The button which triggers the ajax call
*/
var button = $("#clickme");
/**
* Register the click event
*/
button.click(function() {
$.ajax({
url: "textarea.html",
type: "GET"
}).done(function(response) {
var text = $(response).filter("#textarea").html();
$("#content").append("<br/><br/><strong>" + text + "</strong>");
});
});
});
})()
So what does index.js do exactly?
As you can see i created an Ajax call to the textarea.html file. The .done function holds the response data. The data inside it can be anything depending on the content of the textarea.html file.
$(response).filter("#textarea").html();
The above piece of code filters out the #textarea div and then gets the innerHTML using the jQuery html() function.
If you want to get the value of the textarea through the [value] attribute, you can replace above line to
$(response).filter("#textarea").val();
I believe you want to do this:
function createLink() {
var textvalue = document.getElementById('sentenceId').value;
document.getElementById("link").innerHTML = textvalue;
document.getElementById("buttonId").className ="hideme";
document.getElementById("sentenceId").className ="hideme";
}
.hideme{
display: none;
}
<textarea id="sentenceId">
</textarea>
<br>
<button id="buttonId" onclick="createLink()">Submit
</button>
<p id="demo">
<a id ="link" href="b.html"/>
</p>
My original code which works is this:
function changeURL() {
var theURL = location.pathname;
var newURL = theURL.replace("/page1/", "/page2/");
return newURL;
}
$('.currentpagediv').load(changeURL() + ' .secondpagedivclass');
Basically, per How can I dynamically add a URL into javascript, to get a second page's div to display on the first page?, I am trying to add new content from second page into the first page.
However, Now I am trying to also add the SECOND PAGE of the second page into the first page, because the way it is set up, it shows page 1, 2, 3, 4, 5 etc pagination at the bottom. I am trying to also show the other pages in the same page.
For example,
<html>
<body>
<div class="currentpagediv">
</div>
<div class="secondpagedivclass">
[CONTENT HERE]
Page 2, Page 3, Page 4, etc.
</div>
</body>
</html>
But I want:
<html>
<body>
<div class="currentpagediv">
</div>
<div class="secondpagedivclass">
[CONTENT HERE]
[Page 2 Pagination Link CONTENT HERE]
[Page 3 Pagination Link CONTENT HERE]
[Page 4 Pagination Link CONTENT HERE]
[etc.]
</div>
</body>
</html>
Original URL that I am inserting, looks like this:
http://theurl.com/page2/somethingsomewhere.html
The pagination pages look like this:
http://theurl.com/page2/somethingsomewhere.html?new_page=2
http://theurl.com/page2/somethingsomewhere.html?new_page=3
etc.
Here is the code I tried first that does not work:
$('.currentpagediv').load(changeURL() + ' .secondpagedivclass' + '?new_page=2');
But I learned it does not work because you can't parse the question mark. I read that instead I should use .search to parse the new page. So I tried this:
function changeURL() {
var theURL = location.pathname;
var newURL = theURL.replace("/page1/", "/page2/");
return newURL;
}
function secondPage() {
var secondURL = changeURL()
var secondnewURL = secondURL.search('new_page', 2);
return secondnewURL;
}
$('.currentpagediv').load(secondPage() + ' .secondpagedivclass');
In the above code, the only difference from the original working code is the addition of the secondPage() function, and adding that function after .load(.
In the code above, I tried to:
fetch the url of current page
modify the url, and then
append ?new_page=2 to the end of the new url, and
add the function secondPage() to create the URL
I am designing a webpage that loads images of a document into the webpage and then will relocate to a specific image (page) based on a variable passed from another page. The code is below. Right now, it does not look like the variable 'page' is being updated. The page will alert
<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
<!-- Javascripts -->
<script type="text/javascript">
var pageCount = 40; /*Total number of pages */
var p; /*Variable passed to go to a specific page*/
function pageLoad(){ /*Loads in the pages as images */
for( i = 1; i<= pageCount; i++){
if(i < 10){
i = "0"+i;
}
document.body.innerHTML += "<div class='page'><a id='page" + i +"'><img src='pages/PI_Page_"+ i +".png' /></a></div>";
if( i == pageCount){
gotoPage(p);
}
}
}
function gotoPage(pageNum){ /* Moves webpage to target page of the PI */
window.location = ("#page" + pageNum);
alert(p);
}
function Test(){
window.open("./PI.html?p=15","new_pop");
}
</script>
</head>
<body onload="pageLoad()">
<div class="ExtBtn" onClick="Test()">
<img alt="Exit" src="design/exit_btn-02.png" />
</div>
</body>
</html>
The function TEST() was set up to allow me to have a link to re-open the page with p set to 15. The page opens, however, the function gotoPage() still alerts that p is undefined. Any ideas why that is?
Variables passed in the URL do not automatically become variables in JavaScript. You need to parse document.location and extract the value yourself.
p is never set a value anywhere so of course it will be undefined. You need to pull the value from the query string manually, JavaScript does not magically get the query string value for you.
Use the function here: How can I get query string values in JavaScript? to get the value.
Also why are you checking for the last index, set the go to call after the for loop.
Here is your code with the correct alert(p) working:
http://js.do/rsiqueira/read-param?p=15
I added a "function get_url_param" to parse url and read the value of "?p=15".