window.location not refreshing to the existing URL - javascript

I have a PHP page with implementation of jQuery horizontal tabs. I have added a jQuery script so that the page URL reflects the tab#. I have a form on the page and upon form submission I need to refresh and stay on this same page to include the jQuery correct tab number.
This is the code to add the jQuery tab number to the URL:
<script>
jQuery(function($) {
$("<p>").html("Loaded at " + new Date()).appendTo(
document.body
);
showTab(location.hash || "#tabs-1");
$("#nav a").click(function() {
var hash = this.getAttribute("href");
if (hash.substring(0, 1) === "#") {
hash = hash.substring(1);
}
location.hash = hash;
showTab(hash);
return false;
});
function showTab(hash) {
$("div.tab").hide();
$("#tab-" + hash).show();
}
});
</script>
The full URL of the page is http://somedomain.com/includes/nonadmin_user_profile.php#tabs-5 and includes the tab number for the jQuery horizontal tab.
I am using this script to refresh and stay on the same page: echo "<script>window.location=window.location</script>";
On refresh here is the problem as it lands at this URL which does not include the tab number. http://somedomain.com/includes/nonadmin_user_profile.php
Any suggestions would be appreciated very much.
Here is another detail: The problem described above does not occur if I merely refresh the page with the browser refresh button or if I right click the page and refresh. In this instance the page refreshes and stays on the full url with the tab#.

Per Disaster Faster's request, the issue encountered was simply that the browser was not going to the desired location of the page. The form data was successfully submitted and correct page was loaded.
The solution to his issue was modifying the form's action attribute to include the location information (similar to adding location information to an anchor).
Original:
<form action="nonadmin_user_profile.php" method="post">
New:
<form action="nonadmin_user_profile.php#tabs-5" method="post">
Original Post:
The window.location = window.location redirect should include the location information.
JSFiddle: http://jsfiddle.net/6dqcmh9d/
If you click the button first, it'll report the URL with the location information because it hasn't been added to the URL. Then click the link and re-click the button. You'll receive the URL with the location information added.
If you want just the location information, you can use window.location.hash, but this will only produce the location on the page, not the URL of the page.
The problem you'll run into will be with the form submission. To submit a form without changing the page, you'll either have to submit the form to a new window (add target="_blank" to the form) or implement AJAX. In either case, we'd need a little more of your code to help with integrating it properly.

It is likely that the tab controls are being handled with onclick events or something similar, and are not listening for hash changes onload. You'll likely need to add some custom JS to force the tab change if there's a hash change.
What's wrong with using the reload() method?
document.location.reload(true);
From the docs:
The Location.reload() method Reloads the resource from the current
URL. Its optional unique parameter is a Boolean, which, when it is
true, causes the page to always be reloaded from the server. If it is
false or not specified, the browser may reload the page from its
cache.
If you need to integrate it into a PHP echo struct, use:
echo '<script>document.location.reload(true);</script>';

You should use reload() to refresh the page, eg:
window.location.reload();
Or given your example:
echo "<script>window.location.reload();</script>";

Related

Refresh Page with URL Hash after Submitting Form with jQuery Tabs

I'm a long time self taught user, just never had an issue that wasn't already answered in some form or another. Awesome community thank you all!
So I am dumbfounded as to why javascript will not properly refresh my page.
I have a very large page that I use with jquery and vertical tabs tagged with url hashes. This is a new function I recently added after updating to the newest version.
Upon clicking submit the form refreshes and if $_POST[update] is set it will run a set of queries. Then I have a javascript timeout that refreshes the page (ideally to the correct tab ex: home/database.php?file=101#tab3)
an excerpt of my messy code:
if(isset($_POST['update']))
{ do a bunch of sql stuff
....
<pre>
<?PHP
//unset update variable
$_POST = array();
//print_r(get_defined_vars());
?>
</pre>
</br>
<script type="text/javascript">
function Redirect() {
$('#redirect').trigger('click');
}
var currenturl = window.location.href;
document.write("<form action=" + currenturl +"><input type=submit name=redirect value=Redirect></form>");
document.write("</br>You will be redirected back to the file in 2 seconds.");
setTimeout('Redirect()', 2000);
</script>
<?php
mysql_close($conn);
}
else
{ display usual data....check boxes etc
Now I've tried refreshing in every conceivable way. I clear out the $_POST array so the page should reload displaying information, but it doesn't. However my confirmation of queries being ran show that 0 rows updated, so its not triggering the sql but also isn't properly refreshing still.
I found a function that stored the last clicked tab in the browsers session, however when you switch files, it would skip to that tab. Instead I would want to show the default tab.
I even tried made a button that on click it goes to the proper url which is shown above. It works when I click it manually but does not work when I trigger it via javascript. Even goes to the appropriate tab.
I am updating the url in the address bar using the below function. Also using the latest version of chrome.
<script>
$( "#tabs" ).tabs({
activate: function(event, ui) {
window.location.replace('#' + $(ui.newPanel).attr('id'));
var curTab = $(ui.newPanel).attr('id');
console.log(curTab);
}
});
</script>
Why don't you instead of sending that number after <form_url>?<params>#3 send that number as a request param in the url, for example like this <form_url>?tab=3?

Go back to the actual previous page regardless of a form post error

I have a page with a form. On this page there is also "go back to previous page" link, which uses the following JavaScript:
window.history.go(-1)
When the form is posted and there is a validation error, the website returns the user to the same form page. However, clicking on this link in case of a form validation error gets the user to the form page before its submission, not the actual, different previous page.
How can I get the user back to the actual previous page by ONLY using JavaScript? Please note that there could be multiple times of form submission with errors.
You could probably use location.replace() in your redirect after validation error.
This will erase the current page location from the history and replace it with the new one, so it has no effect on page history.
Another option is to use sessionStorage to check if the URL has actually changed after going back one page in the history.
window.onload = function() {
document.getElementById("back").onclick = function() {
sessionStorage.setItem("href",location.href); //store current page into sessionStorage
history.go(-1); //go back one page
};
if (location.href == sessionStorage.getItem("href")) {document.getElementById("back").click();} //if current page is the same as last one, go back one page
else {sessionStorage.removeItem("href");} //clear sessionStorage
};
In the demos below (SO doesn't allow sessionStorage) I had to simulate both "going through the history", and "page load for every history item", so the code looks a little different, using an array and other vars and functions, but the principle should be the same:
codepen: https://codepen.io/anon/pen/OgBgGg?editors=1011
jsfiddle: https://jsfiddle.net/j0ddnboq/2/
You could store the "actual" previous page in a hidden form field on initial load and send this along with the form, then in your "go back to previous page" link js you could access that data.

How to reload page after inserting data in database

I have created a form which insert the location of some users in database and these data should appear in the page. The problem is that the page doesn't reload by itself after I fill the form but I have to make a page reload.Or if the page is opened in another browser it doesn't reload. Is there a way that this page reloads by itself without making any action after I insert some data in database from this form?
Use the assign() method. The assign() method is supported in all major browsers.
window.location.assign(data); "data being the URL"
or
window.location.href
function myFunction() {
location.assign("http://www.example.com");
}
<button onclick="myFunction()">Load new document</button>
Ok thanks! Functions onClick eventhough I have an ng-click in side this button?
Yes it will still function properly. See JSFiddle demo
Edit: I saw you had this in your code?
window.history.back(); or location.reload();
consider replacing with with:
window.location.replace("pagehere.html");
You can refresh the page after your completing your operation using jquery as
Javascript 1.0
window.location.href = window.location.pathname + window.location.search +window.location.hash;
// creates a history entry
Javascript 1.1
window.location.replace(window.location.pathname + window.location.search + window.location.hash);
// does not create a history entry
Javascript 1.2
window.location.reload(false);

How to change URL path when paging using ajax + jQuery

I am using ajax post requests for doing paging on a feed in my site. When getting the post request data I am reforming the page by clearing previous data and rendering the new data that came from the request. I want to be able to change the URL as well so saving the new page link will get the user to the current page.
Example:
User on page example.com/feed - seeing content of page #1
User clicking to get to page #2 -> ajax post is send and data on the page is changed using js (no refresh)
URL is still example.com/feed but the content is of example.com/feed?page=2
How can I set the URL to point to the new page without triggering a refresh (no redirect) ?
I am using Nodejs + express.
I understand you are aiming at a single page application.
While keeping the url is nice, note you might want distinct urls for directly accessing different parts of your application. Still, you can load content with AJAX and keep a smooth application. The way to go is using the hash part of the location.
The Sammy.js framework gives you a nice base to build upon, you can try it out.
You can use history pushstate but some browsers does not support.
history.pushState({id: 'SOME ID'}, '', 'myurl.html');
And don't forget about window.onpopstate, it pops if user clicks back button.
Redirect the user to an anchor point.
Page 2
And in your document.ready:
if (window.location.hash.length > 1){
var pageNumber = window.location.hash.substring(1);
loadPage(parseInt(pageNumber));
} else{
loadPage(0);
}
I don't believe it is possible to change the query part of the URL without triggering a refresh (probably due to security issues). However you may change the anchor and use an event listener to detect when the anchor is being changed.
//Listener
$(window).on('hashchange', function() {
if(loaction.hash.length > 1) {
//The anchor has been changed.
loadPageWithAjax("example.com/feed.php?page=" + location.hash.substring(1));
} else {
//Load standard page
...
}
});
Change the anchor to load new feed
Page 2
Remember to not use an anchor that is used as an id, since this makes the browser scroll to that element.

How to capture the destination url in onbeforeunload event

I want to use onbeforeunload to give a message to users before leaving certain pages.
Is it possible to know which url they are supposed to jump to at the onbeforeunload event?
Thanks
Is it possible to know which url they are supposed to jump to at the onbeforeunload event?
No, definitely not. The onbeforeunload event tells you only that the page is about to be unloaded, but not why.
It depends on how the user is leaving the page.
If they are typing an url in the address bar - then you're out of luck. As far a I know there's no way to capture the url of an address bar jump.
If they are clicking on a link contained somewhere on the page - that you can use the click event to capture the url and then decide how you want to handle things.
I posed a similar question
How can i get the destination url of a link on the web page in the javascript onbeforeunload event?
because I had a project to fix a wholesale order form. During the process of filling out an order my client's customers would go back to the catalog to check on a product's detail page and loose the current information on their order form.
By using the code below (which uses JQuery though I'm sure you could create the same thing in pure Javascript if you had to) I could tell when the user clicked a link that would leave the order form and then give them the option of opening the link in a new window/tab or loading the url in the current window and loosing their form data, or just returning to the form. This code works with all of the major browsers, at least their more recent versions.
$('body a').click(function(e) {
//if link references a page element
if ($(this).attr('href').charAt(0)=="#") {
return;
}
//check if link is to same window
var pathname = window.location.pathname;
var pathname2 = $(this).attr('href');
pathname2 = pathname2.replace(/^.+\.\//, '');
if (pathname.indexOf(pathname2) >= 0) {
//link clicked is contained on same page
//prevent page from getting reloaded & losing data
e.preventDefault();
e.stopImmediatePropagation();
e.stopPropagation();
return;
}
//link clicked on is another page
if (hasMerchandise) { //var to indicate user has items on order form
//give user options: leave page, open link in other page, stay, etc.
// $('.popupForm-handleExitRequest').click(); //roll your own code
//prevent page from getting reloaded & losing data
//in case user wants to cancel page change or open link in another window
e.preventDefault();
e.stopImmediatePropagation();
e.stopPropagation();
} else {
//load new page
$(this).removeAttr('target');
}
});

Categories

Resources