Save record on page leave - javascript

I am saving records on save button click, if user don't click save button and navigate to another page while clicking on some link even then i want to call the save method.
How can I achieve this functionality?
please provide some sample code ...
thanks in advance for your help

You can make ajax request on
window.onbeforeunload = function(){
////make ajax request
}
Or can prevent the user by giving confirm box
function showalert() {
if (!confirm('Are you sure you want to exit without saving changes?')) {
////make ajax request
}
else {return true;}
}
window.onbeforeunload = function(){ showalert }
For example check this out when I leave this page while answering SO prevent me

Use an ajax post, triggered by window.OnBeforeUnload() to let yourself know that the user has left the page, and pass any information you need.

Well since you want to call the save method even if the user navigates to another page or link
what u need to do is set a hidden field for eg. suppose hdnSave and set its value to say 0
Now when the user navigates or clicks on any another link first check if this hidden field value(hdnSave) is set to 1 or not.If not then Call Save Method.So this hidden Field can be used as an indicator of whether Save Method has been called or not.
Similarly you can use a session(in c# code) for the same purpose as well.

Related

Define a reference site for the history.back button

We want to have a back button in our site
but history.back in javascript does not help us.
We need this function only run on the site and if the user comes from other site, clicking the return button on the previous site should not return.
In fact, we want a return button to run on our site only.
my code is
<i class="fas fa-arrow-left"></i><span class="btn-text">Back</span>
This only works for your own made back button and won't work with the browser back button
There is two ways to achieve that: a simple but not always reliable method and a complex one but always good.
1- The simple method
You use document.referrer and ensure the domain is yours before calling history.back().
2- The complex method
You could register a JavaScript function on page load to get the first URL the internaut land which you could store using history.pushState. Before calling the back function, you could ensure this is not that page. Though, this idea is not complete as the user could probably have landed on this page twice. i.e. Home->Product->Home. I'll let you search for further code that would let you counter this problem.
This code checks the history of back button of the browser on its click event:
$('#backbtn').click(function () {
if (document.referrer.includes(window.location.hostname)) {
window.history.back();
} else {
window.location.href = "/your/path";
}
});

How to track a user coming from a certain URL to trigger a function using JavaScript

I am wanting to trigger a function that will display all events but only when the user comes from a URL with /events/ in it.
Right now I am using referrer to take the user back to the page and to scroll to the last event they clicked on. But if the event they clicked on has to be loaded by clicking 'view more' it will just scroll to the bottom of the page. I need all the events to collapse when the user hits the return button.
Any help is much appreciated!
You can achieve what you're trying to do with localStorage:
if(!!localStorage.getItem("isEventsInPath")) {
// user came from /events
}
var isEventsInPath = document.location.pathname.includes("/events/");
localStorage.setItem("isEventsInPath", isEventsInPath);
// keep the order intact!
You can use the following to parse the URL and call your function:
$(document).ready(function(){
if(document.location.pathname.includes("/events"))
{
//CALL YOUR FUNCTION
}
});
This parses the path name and checks if /events exists in it.

javascript history.back losses the search result

Page A:
$(document).ready(function () {
bindData();
});
function bindData() {
$('#searchbtn').bind('click', function () { SearchResult(); });
}
function SearchResult() {
ajax call...
}
Page A HTML:
<input type="button" id="searchbtn" />
Page B Details---> this page comes after selecting a specific search result from page A search list
Back<br />
Now when I go back to the Page A I can see my search criteria's as they were selected but the result Div is gone. What I am trying to do is I want the search list to stay when the Page comes back.
I think what I can do here is some how call the searchbtn click event again when the page comes back so the list will come-up again. Can anyone tell me how to fire the searchbtn click event only when the page comes back from Page B. or point me in the right way of doing this..
Thanks
The Browser Back button has long been problematic with AJAX. There are scripts, workarounds, and techniques out there (depending on the framework that you want to use).
Since it appears that you are using jQuery (based on your posted JavaScript syntax), here is a link to another Stackoverflow post regarding back button jQuery plugins.
history.back() will return you to the last URL visited, meaning that any ajax calls made during the user's visit will not be automatically repeated. Your browser may automatically restore your form selections, but the SearchResults() function is only called by a click event, not a selection event.
You can bind URLs to ajax states using a framework like sammy.js. That way, history.back() would take you to a URL associated with SearchResults().
function bindData() {
var chkinput1 = $("input:checkbox[name=x]:checked").length;
var chkinput2 = $("input:checkbox[name=y]:checked").length;
if (chkinput1 > 0 && chkinput2 > 0) {
SearchResult();
}
$('#searchbtn').bind('click', function () { SearchResult(); });
}
I know this is the worst way to achieve this result but I think instead of using any other plugins to add complexity we will go with this for now. If anyone else is looking for the same question let me tell you again this is not the best practice as on returning back to the history we are calling the search result again depending upon the cached input selection of checkboxes and generating the whole ajax call again to display the list. On the first request I am caching the list and setting sliding expiration so its not taking anytime to comeback and so everyone lives happily.

Javascript - Reload page after form submit with target="_blank"

I'm trying to achive the following:
On page A we have an access restricted Link to page B. The access restriction is handled on the server side in PHP.
When a user clicks on this link to page B we display a modal dialogue on page A (via javascript) with a form, having the link's href (B) as the action. (To give the user an immediate feedback. The fallback is to redirect him to a login form that redirects him to the site he wants to access.)
This system works quite well.
But now comes my question:
We have access restricted links that should be opened in a new window.
Now if I use target="_blank" on the form the user stays logged out on the page he came from (A), that is still open in the background.
Is there a way to reload the page (A, in the background) right after the form has been submitted to the new window (B)?
My first idea was to use window.location.reload(); in the submit handler on page A.
This didn't work in chrome and from what I understand could create a race condition.
Another idea would be to log the user in via an ajax call and open a new window through javascript. Is there a way to do this without having to deal with pop-up blockers?
I implemented the idea of lostsource (see below) with one slight addition.
As I need to reload only once, the timer of setInterval can be stopped if the cookie changed.
var ri=setInterval(function() {
if(oldCookie != document.cookie) {
// assuming a login happened, reload page
clearInterval(ri);
window.location.reload();
}
},1000); // check every second
I still love the idea. stackoverflow is awsome!
Assuming you're storing PHP session information inside a cookie, you might be able to monitor your document.cookie for changes.
Before submitting the form store the value of the current cookie and monitor it for changes with a timer:
form.onsubmit = function() {
var oldCookie = document.cookie;
var cookiePoll = setInterval(function() {
if(oldCookie != document.cookie) {
// stop polling
clearInterval(cookiePoll);
// assuming a login happened, reload page
window.location.reload();
}
},1000); // check every second
}
On the parent page, do you have any visual/functional changes because of the login? As in any new actions possible?
If not, then you dont have to do anything as you would be checking for login on every action from the parent page, you can check for permissions along with that.
If there are changes or additional functionalities, you can call a javascript function in the parent, say reloadMe, using window.opener.reloadMe()
Why not just a simple setTimeout
setTimeout(function(){ location.reload(); }, 1000);
It is a bit hacky, but seems appropriate for your situation.

How to stop unloading the page?

I have a page where user needs to enter some data and click save to validate the changes, but my problem is if the user is trying to close the browser window or click on a different link to navigate to a different page..I need to delete all the entries the user has saved so far..
I am doing it the following way
window.onbeforeunload = function()
{
if(confirm('Are you sure you want to navigate'))
{
//Invoke `enter code here`server side method
}
else
{
// return false;
}
}
Everything works fine if he click on Yes, the problem comes when he click on "No"..Even if he click on No..the page unload method is getting called and it is redirected to a different page..but I want it to stay in the same page in same state...can you please help me in achieving this.
Thanks and appreciate your response....
You cannot stop the user from leaving the page. What you can do is alert a message to them, asking if they want to leave or not.
The window.onbeforeunload event should return a string (and only a string). This string will be printed on the alert box made by the browser.
You cannot use your own alert box, or block the user from leaving (or redirect them).
window.onbeforeunload = function(){
return 'Are you sure you want to leave?';
};
Or with jQuery
$(window).on('beforeunload', function(){
return 'Are you sure you want to leave?';
});
When a user leaves the page, you can use the onunload event to make an AJAX call (you may need to use async: false here).
Example:
$(window).unload(function(){
$.ajax({
url: '/path/to/page/',
async: false, // this may be needed to make sure the browser doesn't
// unload before this is done
success: function(){
// Do something
}
});
});
NOTE: Instead of doing this, why don't you just save everything when the user is completed? Instead of saving it and then removing it if the user doesn't finish?
First of all: you can't! It's impossible. onbeforeunload only accepts a string as return value and will then close if the user wants that.
But then think about what happens if the computer is being without energy and shuts down? Or the browser will closed by the Task Manager? Or even more "realistic": The internet connection get lost! => Then you got invalid data states too!
You are trying to solve a false problem! Your problem isn't this function, your problem is the state of your formular!
Why do you need some kind of function? Do you saving the data before he clicks on save? Then don't! Or make sure to have another query which detects unfinished data in your database and delete it after a timeout!
onbeforeunload only accepts a string as return value. That string will be displayed by the browser with the option to stay on the page or leave it. But that's ll you can do.
You can use something like this, just call the following function on your page
function noBack() {
window.onbeforeunload = function(){window.history.forward()}
}
this disables Back button if window.history is clean, otherwise it works only first time.

Categories