I am trying to maintain few objects in cookie to restore some settings. Initially i tried in window.unload to save and restore settings using cookie.It worked in full page load. But it didn't work in my case as whole page is not loading just replacing the specific content using ajax post(ajax load). So can you tell me in which event can i save those values in cookie to restore back while using ajax post ?
I tried the below code in window.unload event
window.onunload = function (e) {
var gridObjModel = $("#Grid");
var myCookie = escape(JSON.stringify({
"CurrentPage": gridObjModel.pageSettings.currentPage,
"SortedColumns": gridObjModel.sortSettings.sortedColumns,
"GroupedColumns": gridObjModel.groupSettings.groupedColumns
}));
document.cookie = myCookie;
}
You could try with the following:
$(window).on("unload", function (e) {
var gridObjModel = $("#Grid");
var myCookie = escape(JSON.stringify({
"CurrentPage": gridObjModel.pageSettings.currentPage,
"SortedColumns": gridObjModel.sortSettings.sortedColumns,
"GroupedColumns": gridObjModel.groupSettings.groupedColumns
}));
document.cookie = myCookie;
});
When you do a ajax load just trigger unload before:
$(window).trigger("unload");
$("#foo").load(someUrl);
Related
I have used history.pushState() and now if the user refreshes the page then it is refreshing current URL which is not an original URL.
I tried detecting refresh page with a cookie, hidden filed but it is not working.
window.onload = function() {
document.cookie="PR=0";
var read_cookies = document.cookie;
var s = read_cookies;
s = s.substring(0, s.indexOf(';'));
if( s.includes("1"))
{
window.location.href = "https://www.google.com";
}
else{
document.cookie="PR=1";
}
loadURL();
};
function loadURL()
{
document.cookie="PR=1";
document.getElementById("visited").value="1";
var str="abc/b cd";
str=str.replace(/ /g, "-");
history.pushState({},"",str);
}
when user is refreshing the page I need original URL on that time.
This might be helpful. But you need control over the pushed url.
// this goes to your 'original' url
window.addEventListener('beforeunload', function (event) {
sessionStorage.setItem('lastPage', window.location.href)
}
// page with your pushed url
if (sessionStorage.getItem('lastPage') === 'PAGE_YOU_DONT_WANT_TO_BE_REACHABLE_DIRECTLY') {
window.location = 'PAGE_YOU_WANT'
}
I'm interested what the use case for this is. As far as my knowledge goes you can't suppress the refresh event completely.
I have this function below, however I want to make it work on windows load and show the result without clicking the button.
This is the code I use https://raw.githubusercontent.com/SuyashMShepHertz/indexedDB_sample/master/index.html
How to do this?
$("#getBtn").click(function(){
var type = 'permanent';
var request = db.transaction(["hashes"],"readwrite").objectStore("hashes").get(type);
request.onsuccess = function(event){
$("#result").html("Name : "+request.result.name);
};
});
just put your code in
$( window ).load(function() {
//Code Here
});
If you need it both on click and initially when the page loads, make it a reusable function:
function doTheThing() {
var type = 'permanent';
var request = db.transaction(["hashes"], "readwrite").objectStore("hashes").get(type);
request.onsuccess = function(event) {
$("#result").html("Name : " + request.result.name);
};
}
Then call it from both places you need it:
On page load
On click
To call it on page load, just make sure your script is at the end of the HTML (just before the closing </body> tag; this is best practice unless you have a good reason for doing something else) and call it:
doTheThing();
If you can't put the script at the end of the HTML, you can use jQuery's ready callback instead:
// Concise, but easy to misunderstand:
$(doTheThing);
// Or more verbose but also more clear:
$(document).ready(doTheThing);
(See note below about doing it directly or indirectly.)
To call it on click, hook it up, either directly or indirectly:
// Directly
$("#getBtn").click(doTheThing);
// Or indirectly
$("#getBtn").click(function() {
doTheThing();
});
The only reason for hooking it up indirectly would be to avoid having it receive the event object jQuery will pass it automatically, and to avoid having its return value examined by jQuery to see if it should stop propagation and prevent the default event action.
To avoid creating globals, I'd make sure the entire thing is in a scoping function:
(function() {
function doTheThing() {
var type = 'permanent';
var request = db.transaction(["hashes"], "readwrite").objectStore("hashes").get(type);
request.onsuccess = function(event) {
$("#result").html("Name : " + request.result.name);
};
}
doTheThing();
$("#getBtn").click(doTheThing);
})();
just put it in $(document).ready, like this
$(document).ready(function(){
var type = 'permanent';
var request = db.transaction(["hashes"],"readwrite").objectStore("hashes").get(type);
request.onsuccess = function(event){
$("#result").html("Name : "+request.result.name);
};
});
I have two server side php scripts:
1: /addit.php - which creates a pdf file on server based on current ID given
2: /viewit.php - which downloads the pdf file to the browser window.
Both these scripts work fine btw.
However I want to combine a single onclick function to run "addit.php" and then view the file by opening the file "view.php".
So I am using the original code that was creating the file ok and then adding in a window.location but they won't work together. If I remove the window.location the first part of code works fine, If I include it, the first part stops working and only the window.location works.
Sorry for being stupid, thanks.
function download_invoice() {
$(document).on('click','.downloadit',function(id){
var current_element = $(this);
var id = $(this).attr('id');
var ida = $(this).attr('id')+"A";
var idicon = $(this).attr('id')+"icon";
$.post('myaddress/addit.php',
{ list_entry_id: id },
$("#infobox_data_button2").fadeTo(1001,.33)
);
});
window.location="myaddress/viewit.php";
};
You should move window.location="myaddress/viewit.php"; to ajax callback as below. Otherwise it fires before you get response from server.
$.post('myaddress/addit.php',
{ list_entry_id: id },
function() {
$("#infobox_data_button2").fadeTo(1001,.33);
window.location="myaddress/viewit.php";
}
);
The window.location is out of the event. While you run the ajax (asynchronous) to 'myaddress/addit.php' the redirect will occur killing the process.
You need to put the window.location in a success callback, therefore in the event.
function download_invoice() {
$(document).on('click','.downloadit',function(id){
var current_element = $(this);
var id = $(this).attr('id');
var ida = $(this).attr('id')+"A";
var idicon = $(this).attr('id')+"icon";
$.post('myaddress/addit.php', { list_entry_id: id }, function(data){
$("#infobox_data_button2").fadeTo(1001,.33);
// Here!
window.location="myaddress/viewit.php";
});
});
// Abandoned
//window.location="myaddress/viewit.php";
};
I am trying to figure out how can I refresh a target page when visited either by a hyperlink or the back button, or even a button. Any ideas ? I have tried almost any solution I could find online and still can make the target page refresh after visited.
Well you can refresh the page using JavaScript with this code:
location.reload();
But if you don't put a condition on it, it'll refresh forever, right?
You'll need to describe your issue in more detail.
if you want to reload page when page full loaded use this JS:
$( document ).ready(function() {
location.reload();
});
if you want timer when page loaded and then reload it use:
$( document ).ready(function() {
// reload after 5 second
setTimeout(function() {
location.reload();
}, 5000);
});
if you want reload only first time use this:
function setCookie(cookieName,cookieValue,nDays) {
var today = new Date();
var expire = new Date();
if (nDays==null || nDays==0) nDays=1;
expire.setTime(today.getTime() + 3600000*24*nDays);
document.cookie = cookieName+"="+escape(cookieValue)
+ ";expires="+expire.toGMTString();
}
function getCookie(cookieName) {
var theCookie=" "+document.cookie;
var ind=theCookie.indexOf(" "+cookieName+"=");
if (ind==-1) ind=theCookie.indexOf(";"+cookieName+"=");
if (ind==-1 || cookieName=="") return "";
var ind1=theCookie.indexOf(";",ind+1);
if (ind1==-1) ind1=theCookie.length;
return unescape(theCookie.substring(ind+cookieName.length+2,ind1));
}
So, you would tie it together like this:
$(function() {
var skipModal = getCookie('skipModal');
if (!skipModal) { // check and see if a cookie exists indicating we should skip the modal
// show your modal here
setCookie('skipModal', 'true', 365*5); // set a cookie indicating we should skip the modal
}
});
show this link:
Fire jquery script on first page load, and then never again for that user?
I have made a solution for my website which includes using ajax to present the general information on the website. In doing this, I am changing the URL every time a user loads some specific content with the window.history.pushState method. However, when I press backspace or press back, the content of the old url is not loaded (however the URL is loaded).
I have tried several solutions presented on SO without any luck.
Here is an example of one of the ajax functions:
$(document).ready(function(){
$(document).on("click",".priceDeckLink",function(){
$("#hideGraphStuff").hide();
$("#giantWrapper").show();
$("#loadDeck").fadeIn("fast");
var name = $(this).text();
$.post("pages/getPriceDeckData.php",{data : name},function(data){
var $response=$(data);
var name = $response.filter('#titleDeck').text();
var data = data.split("%%%%%%%");
$("#deckInfo").html(data[0]);
$("#textContainer").html(data[1]);
$("#realTitleDeck").html(name);
$("#loadDeck").hide();
$("#hideGraphStuff").fadeIn("fast");
loadGraph();
window.history.pushState("Price Deck", "Price Deck", "?p=priceDeck&dN="+ name);
});
});
Hope you guys can help :)
pushState alone will not make your page function with back/forward. What you'd need to do is listen to onpopstate and load the contents yourself similar to what would happen on click.
var load = function (name, skipPushState) {
$("#hideGraphStuff").hide();
// pre-load, etc ...
$.post("pages/getPriceDeckData.php",{data : name}, function(data){
// on-load, etc ...
// we don't want to push the state on popstate (e.g. 'Back'), so `skipPushState`
// can be passed to prevent it
if (!skipPushState) {
// build a state for this name
var state = {name: name, page: 'Price Deck'};
window.history.pushState(state, "Price Deck", "?p=priceDeck&dN="+ name);
}
});
}
$(document).on("click", ".priceDeckLink", function() {
var name = $(this).text();
load(name);
});
$(window).on("popstate", function () {
// if the state is the page you expect, pull the name and load it.
if (history.state && "Price Deck" === history.state.page) {
load(history.state.name, true);
}
});
Note that history.state is a somewhat less supported part of the history API. If you wanted to support all pushState browsers you'd have to have another way to pull the current state on popstate, probably by parsing the URL.
It would be trivial and probably a good idea here to cache the results of the priceCheck for the name as well and pull them from the cache on back/forward instead of making more php requests.
This works for me. Very simple.
$(window).bind("popstate", function() {
window.location = location.href
});
Have same issue and the solution not working for neither
const [loadBackBtn, setLoadBackBtn] = useState(false);
useEffect(() => {
if (loadBackBtn) {
setLoadBackBtn(false);
return;
} else {
const stateQuery = router.query;
const { asPath } = router;
window.history.pushState(stateQuery, "", asPath);
},[router.query?.page]