Remove URL Variable on after some time - javascript

I have a div identified as emailsuccess. A user fills out a contact form and submits it he is redirected to http://www.mysiteurl.com?email=success. I have a div that only will display when the URL contains email=success. (Basically it just displays a message "You're email has been sent".) I'd like to have the message display for about 5 seconds, then fade out and remove the email=success variable from the URL so if the user reloads the page or shares it with a friend, they won't be getting notifications that an email has been sent.
Maybe using the .delay() function I have set the integer to 5000 but I do not know how to have the content fade out and remove the variable from the URL.
Here's my code until now:
$(document).ready(function(){
var url = document.location.href;
if (url.indexOf('/Contact-us-a/7.htm?email=success') >= 0) {
$('#emailsuccess').show();
} else {
$('#emailsuccess').hide();
};
});

Unless you limit yourself to browsers that support the History API, you'll have to redirect the browser to a URL that doesn't contain that part of the URL (will cause page reload).
Symfony Framework for PHP solves this using flash variables in templates (has nothing to do with Flash) - variables that are available on the next request, but are deleted on the next. That way, you wouldn't have to pass that state via URL and a refresh of the same URL will not redisplay that message.

Related

Redirecting to previous page in asp.net

I have a web form which contains a submit button which updates the database.
After clicking the button I need to display a message and go back to the previous page after 2 seconds.
Regardless on technologies you use, you can simply store "back link" in the URL as one of the GET parameters and then use this URL to redirect user back to the required page. For example, your link might look like this:
/action/send/?backlink=/path/to/previous/page/
Of course, this link should be URL encoded and will look like this:
/action/send/?backlink=%2Fpath%2Fto%2Fprevious%2Fpage%2F
You can also send this link using POST method, alongside with the query for the database you might send. After the link being passed to the backend, you can place this link as a destination for redirect on the page with the message you want to show. You can use redirect by <meta> tag in HTML document like this:
<meta http-equiv="refresh" content="5;url=/path/to/previous/page/" />
5 — Delay, amount of seconds before refresh will be fired;
url=/path/to/previous/page/ — Path for redirection.
As another solution, you can write JavaScript code which will do the same thing. Minimal implementation will look like this:
<script>
// Wait for page to load
window.addEventListener('load', function() {
// Set the timer for redirection
setTimeout(
function () {
location.href = '/path/to/previous/page/';
},
// Amount of milliseconds before refresh triggered
5000
);
});
</script>
Response.AppendHeader("Refresh", "2;url=page.aspx");
this works.

How to replace content of div tag using JavaScript on back button?

My question is almost similar to question question here.
I am have a standard sidebar homepage, which executes ajax to replace text inside a div tag and show context. All works fine except the back button. The back button redirects to login page.
These are the things I tried : (I am using servlets)
Without any javascript, user is sent to login.jsp on back button, (session is not invalidated).
I have written code in login.jsp to redirect to homepage when user is already logged in.
access = Integer.parseInt(session.getAttribute("access").toString());
if (access == 1) {
RequestDispatcher rd = request.getRequestDispatcher("ajaxContent?url=homepage");
rd.forward(request, response);
//ajaxContent is the servlet loads the sidebar. With the content of homepage in div tag.
}
But back button just displays the previous page, so the java code to check session is never executed.
I tried to add a onbeforeunload function to alert the user on back button.
window.onbeforeunload = function () {
return "Your work will be lost.";
};
But it also displays the alert when saving forms saying "Your data will not be saved", well, that's not a very good way to accept forms, right?
Lastly I tried history.pushState function to replace the history when ever the ajax function is called.
window.history.pushState({}, 'Previous','www.example.com/ajaxContent?url=homepage');
But that just replaces the url in the browser but doesn't load the page. On multiple clicks, it displays login.jsp again. (obviously)
I also found this page which has source code to disable the back button entirely, but I would prefer to make the back button the replace the div tag with the previous content that was in there.

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.

Get current DOM element

I have a functioning site that includes a search function that loads results into a <div> element via a jQuery $.ajax call like so:
$.ajax({
url: '{{ path('order_search') }}',
type: $(this).attr('method'),
data: $('#search_form').serialize(),
success: function (data) {
$('#js-search-results').html(data);
}
});
I'm working in a twig template within a symfony project, thus the url notation. This is working perfectly.
This is on a site that requires login. I have an event listener in symfony that checks for a period of inactivity at each each kernel request (taken from here), and if the inactive period exceeds a maxIdleTime then the user is redirected to the login page.
My problem is that if the user is inactive for a period and then enters a search, the js-search-results div is filled with the login page. What I would like to happen is to have the entire window redirect to the login page. Seems simple, but I haven't figured out how to do it.
One what I thought to handle would for my login page script to check whether it was being loaded into the full window (rather than just a div element), and if not then refresh the entire window. How to do this?
You can check the content inside the variable "data" to check if it contains elements from the login page and then use an if else statement.
if(data.includes("username") && data.includes("password")){
window.location.assign("https://your.login.page.html");
}else{
$('#js-search-results').html(data);
}
It sounds like you want to find out what type of data is there and if it is the login page do a redirect.
Find out if the data contains elements that are in the login page. if it is do a window.location.href = "/login" if not display the search results in the div. send data from backend like {page : "login"}

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.

Categories

Resources