Updating <div> text with value from the previous page - javascript

I'm redirecting the user from another page when they click the "Edit" button using the code below.
$('#editListButton').click(function(){
window.location.href = "http://localhost/yyy.php"; //redirect
// Changes that need to be made
$('#defaultText').remove();
$('#orderList').append('<p' + 'message' + '</p>');
});
The page redirects to the predefined link, after which I need update a html <div> tag with text. But the code coming from the other page does nothing. How can change the text in the div tag?

Pass it in the url.
$('#editListButton').click(function(){
window.location.href = "http://localhost/yyy.php?message"; //redirect
});
Then on the other page
var url = window.location.href.split('?');
var msg = url[1];
$('#defaultText').remove();
$('#orderList').append('<p>' + msg + '</p>');

Once you've triggered an operation that's going to reload the entire page, browsers (not all, but it seems like most) will just quit doing anything to the current page, essentially ignoring any DOM updates from the event loop.
To get around this, it generally works to delay the redirect with a short timeout:
setTimeout(function() {
window.location.href = "http://localhost/yyy.php";
}, 1);
Now the browser doesn't know that the page is to be reloaded, so it'll obey your DOM update request.
edit — If what you're expecting (and it's not really clear from the OP, but it's hinted at in a comment below) is that the code after updating the location should affect the new page, well that's just not how things work. You can put that code in the new page (and pass parameters via the URL you're loading, if necessary) and have it run there, or else you can change the architecture completely and load your new code via ajax.

There are many ways to pass information from one page to another. To give an idea of the concept, somewhat in relation to the question posted, here's one:
Page A:
$('#editListButton').click(function(){
window.location.href = "http://localhost/yyy.php?action=remove&value=" +
encodeURIComponent('ashdahjsgfgasfas');
});
Page B:
var action = /(?:\?|&)action=([^&$]+)/.exec(location.search)
if ( 'remove' === action[1] ) {
var value = /(?:\?|&)value=([^&$]+)/.exec(location.search)
$('#defaultText').remove();
$('#orderList').append('<p>' + value[1] + '</p>');
}

Related

How to get string URL from multiple past pages JavaScript

I am very new to JavaScript. I am trying to make a web application, where a simple back button will go to a specific page I am looking for, one that has the word "search" in it. I don't know the exact URL, because the parameters within that URL change, and I need to keep it consistent to what the user wanted. But this one button should go back to that one page, regardless of the other links that were clicked.
For example:
If I clicked on
Home Page
Main Page
Page 1
Page 1.3
Back
I want the back to always take me to Main Page with the exact parameters it had before, not Home Page.
I tried the following:
The button itself
movieTableBodyElement.append('' + " << Back" + ''); // Building the HTML button, calls the goBackHelper() function
function goBackHelper()
{
// checks if the page directly behind is the Main Page with "search"
if(document.referrer.includes("search"))
{
// if its the main page, exit the function and end recursive call
window.history.go(-1);
}
else
{
// it is not the last page, so go to the past page and check again
window.history.go(-1);
goBackFunction();
}
}
But this takes me to the very first home page. I thought that document.referrer would get me the past URL, but it doesn't seem to be working for me. Is there a way to get the URL from past pages? So if I am on page 2, can I get all the URLs and search for Main Page? Any help is greatly appreciated!
I'm also new to Stack Overflow, so if there is any clarification please don't hesitate to let me know!
document.referrer is not the same as the actual URL in all situations.
Your best bet is to store the URLs in sessionStorage.
Add this snippet of code to your pages:
if (sessionStorage.getItem("locationHistory") !== null) {
var locationHistoryArray = JSON.parse(sessionStorage.getItem("locationHistory"));
locationHistoryArray.push(window.location.href);
sessionStorage.setItem("locationHistory", JSON.stringify(locationHistoryArray));
} else {
var locationHistoryArray = [];
locationHistoryArray.push(window.location.href);
sessionStorage.setItem("locationHistory", JSON.stringify(locationHistoryArray));
}
And this is your goBackHelper() function :
function goBackHelper() {
var searchString = 'search'; //modify this
var locationHistoryArray = JSON.parse(sessionStorage.getItem("locationHistory"));
for (i = 0; i < locationHistoryArray.length; i++) {
if (locationHistoryArray[i].includes(searchString)) {
window.location.assign(locationHistoryArray[i]);
break;
}
}
}
Read about document.referrer here.

Why can't I add parameters to the window.location?

Using Javascript, I'm trying to reload my page and add a parameter before doing so. I've added the alerts to debug why the parameter is not getting passed to the server:
alert('before: ' + window.location.href);
window.location.href = window.location.href + "?advanced_expand=true";
alert('after: ' + window.location.href);
window.location.reload();
What has me perplexed is that the first alert is:
before: http://localhost:3000/orgconf/quick_org_benefit/edit/784
and the second is:
after: http://localhost:3000/orgconf/quick_org_benefit/edit/784
without the parameter added...what gives?
Doing the window.location.reload() afterwards is pointless because setting window.location.href changes the page.
Likewise, window.location.href doesn't actually change until the page changes. That's why you aren't seeing the URL change.
If the page is reloading and it still hasn't changed, make sure your URL rewriting isn't removing GET parameters that come after a ?.

URL hashchange problems with ajax loading

I have a functional wordpress theme that loads content via ajax. One issue that I'm having though is that when pages are loaded directly the ajax script no longer works. For example the link structure works as follows, while on www.example.com and the about page link is clicked then the link becomes www.example.com/#/about. But when I directly load the standalone page www.example.com/about, the other links clicked from this page turn into www.example.com/about/#/otherlinks. I modified the code a little bit from this tutuorial http://www.deluxeblogtips.com/2010/05/how-to-ajaxify-wordpress-theme.html. Here is my code. Thanks for the help.
jQuery(document).ready(function($) {
var $mainContent = $("#container"),
siteUrl = "http://" + top.location.host.toString(),
url = '';
$(document).delegate("a[href^='"+siteUrl+"']:not([href*=/wp-admin/]):not([href*=/wp-login.php]):not([href$=/feed/]))", "click", function() {
location.hash = this.pathname;
return false;
});
$(window).bind('hashchange', function(){
url = window.location.hash.substring(1);
if (!url) {
return;
}
url = url + " #ajaxContent";
$mainContent.fadeOut(function() {
$mainContent.load(url,function(){
$mainContent.fadeIn();
});
});
});
$(window).trigger('hashchange');
});
The problem you are expressing is not easily solved. There are multiple factors at stake but it boils down to this :
Any changes to a URL will trigger a page reload
Only exception is if only the hash part of the URL changes
As you can tell there is no hash part in the URL www.example.com/about/. Consequently, this part cannot be changed by your script, or else it will trigger page reload.
Knowing about that fact, your script will only change the URL by adding a new hash part or modifying the existing one, while leaving alone the "pathname" part of the URL. And so you get URLs like www.example.com/about/#/otherlinks.
Now, from my point of view there are two ways to solve your problem.
First, there is an API that can modify the whole URL pathame without reload, but it's not available everywhere. Using this solution and falling back to classical page reload for older browser is the cleaner method.
Else, you can force the page reload just once to reset the URL to www.example.com/ and start off from a good basis. Here is the code to do so :
$(document).delegate("a[href^='"+siteUrl+"']:not([href*=/wp-admin/]):not([href*=/wp-login.php]):not([href$=/feed/]))", "click", function() {
location = location.assign('#' + this.pathname);
return false;
});
It should be noted that this script won't work if your site is not at the root of the pathname. So for it to work for www.example.com/mysite/, you will need changes in the regex.
Please let me know how it went.

Facebook Changes Page URL but does not actually change page

I was on Facebook and realised that when I change page the page address changes but the page does not redirect but loads via ajax instead.
You can tell because the console does not clear when you click the link but the URL changes.
Weird, but anyone know how it is done?
Facebook runs with massive AJAX calls that changes the page state and the sections.
So to make a page linkable to somebody by copying the URL address, every time you call an AJAX relevant function they updates the URL using a fake anchor "#!" plus the real address.
Simply when you load the real page (using F5 or linking that so somebody) a JS parser catchs the string after #! (if there is) and redirect you to baseaddress + that.
I belive something like this (untested):
var urlstr = new String(location.href);
var urlparm = urlstr.split('#!');
var last = urlparm.length - 1;
if( (urlparm[last] != urlparm[0]) && (urlparm[last] != "/") )
{ var redir = "http://www.facebook.com" + urlparm[last];
location.href = redir;
}
In Google Chrome instead the URL really changes, I'm according that there is an hash somewhere, but I don't know where and how.

How to use javascript to get information from the content of another page (same domain)?

Let's say I have a web page (/index.html) that contains the following
<li>
<div>item1</div>
details
</li>
and I would like to have some javascript on /index.html to load that
/details/item1.html page and extract some information from that page.
The page /details/item1.html might contain things like
<div id="some_id">
picture
map
</div>
My task is to write a greasemonkey script, so changing anything serverside is not an option.
To summarize, javascript is running on /index.html and I would
like to have the javascript code to add some information on /index.html
extracted from both /index.html and /details/item1.html.
My question is how to fetch information from /details/item1.html.
I currently have written code to extract the link (e.g. /details/item1.html)
and pass this on to a method that should extract the wanted information (at first
just .innerHTML from the some_id div is ok, I can process futher later).
The following is my current attempt, but it does not work. Any suggestions?
function get_information(link)
{
var obj = document.createElement('object');
obj.data = link;
document.getElementsByTagName('body')[0].appendChild(obj)
var some_id = document.getElementById('some_id');
if (! some_id) {
alert("some_id == NULL");
return "";
}
return some_id.innerHTML;
}
First:
function get_information(link, callback) {
var xhr = new XMLHttpRequest();
xhr.open("GET", link, true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
callback(xhr.responseText);
}
};
xhr.send(null);
}
then
get_information("/details/item1.html", function(text) {
var div = document.createElement("div");
div.innerHTML = text;
// Do something with the div here, like inserting it into the page
});
I have not tested any of this - off the top of my head. YMMV
As only one page exists in the client (browser) at a time and all other (virtual/possible) pages are on the server, how will you get information from another page using JavaScript as you will have to interact with the server at some point to retrieve the second page?
If you can, integrate some AJAX-request to load the second page (and parse it), but if that's not an option, I'd say you'll have to load all pages that you want to extract information from at the same time, hide the bits you don't want to show (in hidden DIVs?) and then get your index (or whoever controls the view) to retrieve the needed information from there ... even though that sounds pretty creepy ;)
You can load the page in a hidden iframe and use normal DOM manipulation to extract the results, or get the text of the page via AJAX, grab the part between <body...>...</body>¨ and temporarily inject it into a div. (The second might fail for some exotic elements like ins.) I would expect Greasemonkey to have more powerful functions than normal Javascript for stuff like that, though - it might be worth to thumb through the documentation.

Categories