How to maintain state of global vaiable in JavaScript? - javascript

Hi I have script below: Basically I have a navigation anchors "next" and "prev" which increments or decrements currentDate to navigate between days. This means variable currentDate cannot refresh once the page is load. This variable should be like static variable which should maintain its state, however when ajax call comes back this variable is updated each time to new Date().
<script>
var currentDate = new Date();
$(document).ready(function() {
//ajax call to retrieve some values from the server
});
</script>
Is it possible to declare a global variable which doesn't refresh with each ajax call? Or is it better to get the updated date from the server in this situation? Or am I handling this situation wrongly?
Thanks!

The global javascript variable would not normally reset to "new Date()" simply because an AJAX call returns. It would reset if the page is refreshed. Are you sure there isn't a windows.location call or something else in your AJAX return handler that refreshes the page?

currentDate will not change with each ajax call. If it does, then either it's being set somewhere else or the page itself is being refreshed.

State is not maintained between browser reloads. But there are a bunch of possibilites to persist your data, though, and read them on page load again. You could store the data:
using JavaScript local storage (only for HTML5)
by writing to and reading from cookies (like most websites do)
by using the windows pageName as a data store. This is, in my opinion, the most creepy solution :-)
by using a server to persist the stuff (like applications like Gmail do)
On each of these topics plenty of documentation is available out there.

Related

Angular scope variable not saved when using browser back button?

I have a AugularJS controller that have something like the following when initialized
$scope.urlChanged = false;
and the url is like /firstpage/test
There is a button in the page and when user clicks the button, the following is executed
$scope.urlChanged = true;
window.location = '/secondpage/test';
The page goes to /secondpage/test as expected. When clicking the browser back button, the page goes back to /firstpage/test. But the $scope.urlChanged is false, not the final value true. Is this expected in Angular? How do I make $scope.urlChanged = true when going back?
Scope variables are not saved when you navigate. In fact not even services will retain their values/state. When you navigate with browser back you actually request a whole new angular app.
This is not angular's fault. That is how the browser is expected to handle a new request. The way to persist data in this case is saving any data in something that will persists between requests.
As i see it you have three(ish) options:
Save state in cookies: Well supported by almost all browsers but take caution to handle them as clientside cookies or you won't be able to save data on a page you did not submit (excatly your problem with navigate back in browser).
Save server-side. This has the same problems as the server side cookies. You need to post data to the server for it to persist - which you could do with ajax calls and 'auto-save' with a timeout function. You also need a way of tracking who you are so you can get the correct data from the server - which is often done with cookies, but can be done with querystring parameters but also with (basic) authentication.
LocalStorage. This is my favorite option and is pretty well supported, if you don't need to support legacy IE browsers. There are good frameworks designed for angular that makes it easy to use - and some even have fallback to cookies if not supported.
Check out this link for LocalStorage support:
https://github.com/grevory/angular-local-storage
On change of view,new controller comes into picture and the previous view's controller's instance gets finished. Also , as every controller has its private scope which gets destroyed once view is changed to avoid confusion.

Keep timer (setInterval) running while reloading page

Once I load a webpage, I insert some Javscript via the console. I was wondering if it's possible for me to, using either Javascript or jQuery, reload the page (not from cache) while keeping a setInterval that I have running. I'm familiar with location.reload(), but that terminates it.
When you reload a page, the entire page context including all running JS is completely destroyed. You cannot keep a setInterval() running while its host page is reloaded.
You can create a signal for the new page to start the interval going again itself using a cookie, query parameter or local storage value (query parameter is probably the most appropriate). If you go this way, then you need to code the page to look for a specific query parameter and if it finds it, then the page should start the designated setInterval() itself. You can even pass some data in the query parameter (such as how much more time until the next interval should fire, etc...).
Another option is to not actually reload the page, but instead to refresh the content manually by getting new content via an ajax call and then inserting it into the current page. This allowed the current page context and running interval timers to continue running.
Not possible unless you fetch the page using Ajax request, then replace the body while the setInterval Is working

How to use saved variables saved in Javascript file after moving to new HTML page?

I have a javascript function where in one part, I perform an AJAX call and store some information.
In the same function, I move to a new HTML file.
window.location.href = "deals.html";
Once moving to the new deals.html file, how can I access the information I stored earlier?
Thank you for your help.
The information you stored using AJAX function resides in server now, you have to initiate another AJAX function to retrieve that information from the server when you get the new page.
You can write a javascript function to keep the data using cookies and access it in next page. This will be executed just befor redirecting to another page.
There is something called localStorage which is supported by latest browsers, you can use that to store response from first call, and use it second page.
This can only be achieved if you use cookies in JavaScript because, as you are navigating to another html document you loose the status of all the variables in the already executed script.
So before navigating away to another page set as many cookies as required.
References on cookies

How to run a javascript function when ANY page is loaded

I am doing some maintenance work to a fairly large existing site written in PHP & JavaScript. I am trying to set up a "time out" so that the user is automatically logged out after a specified period of time. I think I have the code that will "expire" the users session, but what I need is a way to run a specific javascript function whenever ANY of the pages in the existing system are loaded. I'd rather not manually add a call in each page as this would take forever and would require even more testing.
Is there a way to add a javascript function call to the window or some other part of the DOM to get called whenever a page is loaded?
Thanks for any help!
There are many ways to achieve this. BUT, you will have to first include a reference to the javascript file.
Then, you can, for instance, use jQuery to detect that the DOM is loaded and ready to call a function of yours.
On a side note, can I ask you why you need to call a javascript function? There are probably other ways to do that, like a listener on your server that redirects to a logout page when a session expires.
Write the javascript in a .js file, host it on your server, and link to the .js from all the pages. While this does not apply a global rule, it is the only way I can think of and it won't be a problem for testing as the code will be from one source.
No.
You have to have the javascript function load into every page. But you just have to write it once and then include like:
<script src="logout.js"></script>
and then you'll need to set the timer for the logout
<body onload="setLogoutTimer()">
But in order for every page to have it you either need to explicitly place it in every page.
That depends to your site script. If you're checking your session data on every request this could be done easily.
Add time data for a session's last move, append it to a js script which controls that If it's time to end the session or not. And take action(js redirect or an ajax request)

what happens to javascript variable after a call to the server?

I just began to learn javascript, so here is a silly question :
What happens to a javascript variable after a call to the server? Are all the variables wiped out?
I read somewhere that javascript variable in ajax can act like session or cookie. Is that true?
All of the run-time state is reset whenever the browser does a page-load, such as navigating from foo.com/bar to foo.com/baz. This includes all JavaScript variables, as well as the current DOM. However, asynchronous calls to the server, such as XHR, do not affect run-time state, and all JavaScript variables will stay.
If you'd like to preserve values between page-loads, you can use cookies or localStorage.
It depends, what scope the variable is in. Also, Ajax is different then submitting a page, so your variables are persisted.

Categories

Resources