How to trigger the reload button in jQGrid at set time intervals - javascript

I want my grid to periodically reload and get the data from the url that i specify. Every 5 seconds, i want the grid to get the current data from the url. I have already tried using setInterval and window.timeout but when i do, the grid reloads the data from the browser cache. It does not invoke the url to get the new data.
Is there a way to make the grid reload and get the new data from the url at specific time intervals ?
Basically, i want the reload button to fire automatically every 5 seconds. How can I do this ?
please help
thanks

What you need, is to use the same method you've been using before, but to prevent the browser's cache. One method of doing so, is on the server-side, add a no-cache header to to the HTTP response for that request.
Another way of doing so, is to change the request's URL, so the browser won't look it up its cache. One example is:
var url = "..."; // Your URL
url += "&nocache=" + (new Date()).getTime();

Thanks,
I figured out a way:
window.setTimeout( refreshGrid, 8000);
function refreshGrid()
{
jQuery("#refresh_list").click();
window.setTimeout(refreshGrid, 8000);
}

Related

Make window.location.href load page from Server instead from browser cache

I am making a redirect using window.location.href to Listing view after an Item is added to DB after successful CREATE operation.
But what it does, it simply fetches old page (not showing the newly added item) that was previously in borwser's cache.
I want it to fetch every think from server, just like we use true parameter in document.location.reload(true) to load a fresh copy of page from server.
You can use this:
window.location.href = "http://www.mywebsite.com/products?t="+ (new Date().getTime());
Or:
window.location.href = "http://www.mywebsite.com/products?t="+ Math.random();

Remove parameter from url not working

I'm attempting to remove a url parameter status from the url but in the following alert, the parameter is still there.
var addressurl = location.href.replace(separator + "status=([^&]$|[^&]*)/i", "");
alert(addressurl);
location.href= addressurl;
How do i solve?
You are confusing regex with strings.
It should be:
var addressurl = location.href.replace(separator, '').replace(/status=([^&]$|[^&]*)/i", "");
Javascript context in web pages are to the page you are working on.
When you reload, redirect or move to any other page, javascript changes done in previous page will not be there. This has to be handled from server side.
Refresh repeats the last request to the server, which is going to ignore your javascript changes. Instead navigate to the new url with window.location = addressurl;

Make popup opening after a while even if the user is navigating to other page

I need a bit of help with this javascript code.
I have this code:
jQuery(document).ready(function(){
if (document.cookie.indexOf('visited=true') == -1) {
var fifteenDays = 1000*60*60*24*1;
var expires = new Date((new Date()).valueOf() + fifteenDays);
document.cookie = "visited=true;expires=" + expires.toUTCString();
window.setTimeout(
function() {
jQuery.colorbox({href:"/popup.htm", open:true, iframe:false, innerWidth:600, innerHeight:490});
},
30000 )}});
It's supposed to open a popup after 30 seconds, one time per day. The issue is that the popup it's opening after 30 seconds on stay on a page. It's there any way to make it to open after 30 seconds even if the client navigate to other page ? So, if the user stay 15 seconds on a page and 15 on another, getting the popup.
Thank you in advance
The fundamental issue to overcome here is passing the 'state' between pages. Since you're already using cookies in your example, we'll work with that. You need to set a session cookie with the time the user has been on the site (initially 0). You'd then need to 'poll' the cookie once every so often (every 5 seconds maybe) to update the total time on site count, and read it back. If it's 30 seconds or more, fire the popup.
So instead of using:
setTimeout(function() {
// open alert box
}, 30000);
You'd do something like:
setTimeout(function() {
// Increment 'time-on-site' cookie value by 5000
// Then, if 'time-on-site' cookie value >= 30000, fire popup
}, 5000);
UPDATE
Of course, this requires a lot more back-and-forth to the server, as you need to communicate the updated value every 5 seconds.
No way man. Once the page is unloaded you cannot do anything else. You need to use other resources on server (cookies, session, etc..) to check if the window is already displayed or not.
Yes.
But it's not possible using document.cookie.
You would need to use server-side cookies or HTML local storage/session storage.
Something like, Response.SetCookie("Visited", true). I don't know what you're using as back end.

How to make a script to run on pages that updates with ajax requests?

I have a script that runs on some pages. The problem is that I attach the script on the page load, but all links on the page make requests and change the contents from the response. (The url's hash changes)
I need a way to check when the "page" is finished loading to add my scripts.
The problem:
somesite.com/home (event load is fired)
*user clicks a link*
somesite.com/home#profile (event load isn't fired, the page is
already loaded, but the contents are
being changed through ajax calls)
How can I do that? I'm thinking on adding a watcher that will check the page all the time and call the corresponding script.
How can I check if the page is sending a request and execute something when the request ends? (I guess it's possible since Firebug does that)
You could use setInterval, and check every 500 ms for changes in the location hash:
var oldHash = '';
setInterval(function(){
var newHash = location.hash;
if(oldHash != newHash){
oldHash = newHash;
// do something
}
}, 500);

$(window).unload wait for AJAX call to finish before leaving a webpage [duplicate]

This question already has answers here:
JavaScript, browsers, window close - send an AJAX request or run a script on window closing
(9 answers)
Closed 6 years ago.
Basically, once a user leaves a webpage in my application, I need to call a PHP script with AJAX, which will insert a time spent on the webpage to the database and then leave the page.
It is important to wait for the AJAX request to finish because webpages in my application are not accessible to users unless they have spent a certain time on a previous page (let's say two minutes).
Here is my jquery code:
$(document).ready(function() {
var teid = TEID;
var startTime = new Date().getTime();
$(window).unload(function() {
var timeSpentMilliseconds = new Date().getTime() - startTime;
var t = timeSpentMilliseconds / 1000 / 60;
$.ajax({
type: 'POST',
url: '/clientarea/utils/record-time',
data: 'teid=' + teid + '&t=' + t
});
});
});
How should I change it so it will wait for the AJAX request to end before leaving the webpage?
EDIT:
Or it might be better (easier) to just let the AJAX request be repeated every minute or so. Is that possible?
Well, you can set async: false on your AJAX call to make the browser wait for the request to finish before doing anything else, but note that this will 'hang' the browser for the duration of the request.
$.ajax({
type: 'POST',
async: false,
url: '/clientarea/utils/record-time',
data: 'teid=' + teid + '&t=' + t
});
From the manual:
By default, all requests are sent asynchronous (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.
⚠ WARNING: This answer was posted in 2010 and is now outdated - the XHR specification highlights the following statement:
Synchronous XMLHttpRequest outside of workers is in the process of being removed from the web platform as it has detrimental effects to the end user’s experience. (This is a long process that takes many years.) Developers must not pass false for the async argument when current global object is a Window object. User agents are strongly encouraged to warn about such usage in developer tools and may experiment with throwing an "InvalidAccessError" DOMException when it occurs.
DevTools in Chrome has recently started warning about it, so this change (which has been coming for some years) could be imminent.
The best solution is to use navigator.sendBeacon. It is brand new functionality which is starting to get implemented in new releases of browsers. The function is available in browsers newer than Chrome 39 and Firefox 31. It is not supported by Internet Explorer and Safari at the time of writing. To make sure your request gets send in the browsers that don't support the new functionality yet, you can use this solution:
var navigator.sendBeacon = navigator.sendBeacon || function (url, data) {
var client = new XMLHttpRequest();
client.open("POST", url, false); // third parameter indicates sync xhr
client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
client.send(data);
};
Hope this helps!
How about setting a cookie in the unload handler? The server should see it on the subsequent requests.
<script>
$(window).unload(function(){document.cookie='left_on='+(new Date())})
</script>
for me, yours is not a good idea for the browser to wait before closing...
simply because what if I really want to close it?...
if a page bother a user, it's not good...
my suggestion is, in the page, you wait for 2 minutes (if 2 minutes is the requirements), then send an ajax that the user has done his 2 minutes...
you can then check it on the server side if one has his 2 minutes or not...
It is a bad idea to try and hijack your users' browser, since it will give them a bad feeling and send them away.
If for some reason you want not to produce a new page until the user has spent a minimum time on the previous one, the best thing to do is to pilot server side, i.e. redirecting to the current page until the requested time has passed.
You don't even need to make ajax calls, just store in the session the timestamp of when the page was served, and don't show the following page until a certain amount of time has passed.
Be sure to tell the users they have to wait for a new page to be ready, maybe with a simple javascript countdown.
If you want the user to actually have the page active for a certain amount of time (i.e. not to switch to another tab/window waiting for the two minutes to elapse), well, I cannot propose an effective solution.
use onbeforeunload:
$(document).ready(function(){
window.onbeforeunload = function(){
// $.ajax stuff here
return false;
}
});
This will at least bring the user a messagebox which asks him if he wants to close the current window/tab.
I think it would be much better to use a polling technique as you suggest, though it will cause some load on the web server.
$(document).ready(function() {
var teid = TEID;
var startTime = new Date().getTime();
var ajaxFunc = function() {
var timeSpentMilliseconds = new Date().getTime() - startTime;
var t = timeSpentMilliseconds / 1000 / 60;
$.ajax({
type: 'POST',
url: '/clientarea/utils/record-time',
data: 'teid=' + teid + '&t=' + t
});
};
setInterval(ajaxFunc, 60000);
})
You'll be glad when you can use websockets :)
The jQuery.ajax() method has the option async. If you set it to false the call will block until the response comes back (or it timed out). I'm pretty shure, that calling this, will yause the browser to weit in the unload handler.
Side note: You can't rely on this to work. If the browser gives the user the option to cancel the unload handlers (which some browsers do after a while of waiting), the "time spend on site" will never be updated. You could add a timer to the site, which periodically calls a script on the server and which updates the time. You won't have an accurate value, but in your case, this isn't needed.
If you only need to know if the user was X seconds on the page You could simply set a timeout in the onload handler (using setTimeout(function, ms)) which makes a call if the user has spend the needed time. So there would be no need for a unload handler.

Categories