AJAX $.ajax() and setInterval() only loading when someone is on page? - javascript

I wrote the code below to refresh or reload the page to a div id='bitcoin_blocks_table' and it only does so when someone is on the site.
If nobody is on the site and I come back in 2 hours it didn't update the ones from the past two hours.
Is this because of the AJAX call or could it be because of the script?
Code:
$('#bitcoin_blocks_table').load('./ajax/bitcoin_blocks.php');
var refresh_bitcoin_blocks = setInterval(function() {
$.ajax({
url: './ajax/bitcoin_blocks.php',
type: 'POST',
success: function(blocks) {
$('#bitcoin_blocks_table').html(blocks);
}
});
}, 10000);

It's because the site "works" only when somebody opens it. The intervals work within a client (browser), and once it's closed, so are the intervals... Imagine what would happen if all the periodic JS functions on every site would run (and add up with every new visit) the whole time!
Google "cron job".

run your script
/ajax/bitcoin_blocks.php
via cronjob
see this article

Related

Javascript does not run after aspx page has been loaded

I created a site in Visual Studio 2015 Community Edition starting with the ASP.NET Empty Web Site template. Recently, I needed to add authentication features, so I created a new ASP.NET Web Forms site, and moved all of my pages/files/entire site created in the empty web site to this new Web Forms site template.
Everything works perfectly--except that none of the javascript that used to update my pages dynamically continue to work. All of the javascript functions that previously worked seem to be completely ignored. (I haven't changed anything in the HTML or Javascript code -- the only thing that changed was the ASP.NET template I began with). Even something as simple as tagging the navigation menu to be active will not work, for example:
<script type="text/javascript">
$(function() {
// this will get the full URL at the address bar
var url = window.location.href;
// passes on every "a" tag
$(".Navigation a").each(function() {
// checks if its the same on the address bar
if (url == (this.href)) {
$(this).closest("li").addClass("active");
}
});
});
</script>
This worked perfectly to highlight the active menu previously, but no longer works in the new Web Forms site template. I've also tried moving it from the file header, to the content, and even to a separately referenced file with no avail.
Is there an assembly I need to add to my new project, or is there a global setting in this ASP.NET Web Forms template that could be blocking my javascript from working? Any help would be greatly appreciated. I've been stuck on this problem for over a week now.
Edit: here's a better example to see if I'm missing something more obvious:
This worked previously to dynamically load more information from a database after a page was loaded and the user scrolled to the bottom. The javascript still works to display a message box when the user hits the bottom of the page, but the Web Method in the c# code behind never gets called...
var pageIndex = 1;
var pageCount;
$(window).scroll(function () {
// Everytime that the user scroll reaches the bottom of the page, execute function GetRecords
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
GetRecords();
}
});
function GetRecords() {
// Local variable page index begins at 1, and each time the user scrolls to the bottom of the page
// this number is increased to mark how many times the user has hit the bottom of the page.
// This later marks how many elements have been loaded from the database.
pageIndex++;
// On first scroll, pageCount is null so pageIndex is 2, and function still needs to be executed.
if (pageIndex == 2 || pageIndex <= pageCount) {
// Display a loading bar
$("#loader").show();
window.alert("loading");
$.ajax({
// POST signals a data request
type: "POST",
// This directs which function in the c# code behind to use
url: "databaseLoadDynamic.aspx/GetCustomers",
// The paramater pageIndex, page number we need to load, to pass to GetCustomers(int pageIndex)
data: '{pageIndex: ' + pageIndex + '}',
// Type of data we are sending to the server (i.e. the pageIndex paramater)
contentType: "application/json; charset=utf-8",
// Type of data we expect back from the server (to fill into the html ultimately)
dataType: "json",
// If all goes smoothly to here, run the function that fills our html table
success: OnSuccess,
// On failure, error alert user (aka me so that I know something isn't working)
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
}
}
Thank you so much for all of your help!

Auto refreshing with Javascript?

Sorry if this is a simple question (or answered before), but could anyone tell me how to download a page with JScript? I want to use Javascript to download the page "example.php" on my server every five seconds and compare it with what it was before. If the page changes, I would like the Javascript code to refresh the page hosting the Javascript. Does that make sense ? Somethingl ike:
string downloaded = DownloadPage("example.php");
timer x = new timer(5);
when the timer goes off:
if(DownloadPage("example.php") == downloaded){
RefreshPage();
}
Thanks, and sorry this was probably such an easy question :)
Using the jQuery framework's get function:
$.get('example', function(data) {
if(data == "something")
//perform action
});

JavaScript: don't unload document until HttpRequest is complete

I need to make sure that when someone reloads or closes my page, their progress is saved. To save progress, I do a POST via XMLHttpRequest(), sending the data to server.
I'm triggering this saveData() function inside a window.onbeforeunload event.
The problem is, that saveData() does some calculations, and then calls a sendData(content) to finally actually POST the data.
And if the data I'm processing&sending is large (>100kB), the window seems to close before all the data gets through to the server. (I'm sending an image, and some times I only get half of it on the other side)
The http request is synchronous, xhr.open("POST", url, false), but that doesn't seem to cut it.
So my question is, how can I keep the onbeforeunload function from terminating, UNTIL xhr.readyState == 4? How do I make it wait for that event?
Oh, and setTimeout() will not work. The window will close before the "Time" comes.
This won't work:
if (!jQuery) {
setTimeout(attachCode, 100);
return;
} else {
// continue and close
}
Thanks for any insight!
PS: this shouldn't be "bad practice" since it only takes a few of seconds and I don't want the user to have to save manually. Also, saving while he works (as in, before he closes window), would slow down the app so I can't do that.
[EDIT] As a temporary measure, I resorted to using this trick to auto save the data if the user decides to stay on the page. However, I'd really like to not need to use any alert messages. :(
Disallowing the browser to do it's normal behaviour is normally a bad idea. And with onbeforeunload you can't pause the unload, you can only let the user know, that he/she is leaving the page and then let them decide, whether or not to leave the page - and thus the data unsaved.
So i your case, i would suggest an draft autosave, like you see in Google documents + a warning when the user leaves the page with unsaved data.
Actually you can slow down the browser before unloading. The problem lies in how JS handles the ajax requests.
Quite a while ago I had to do a quick and dirty hack about almost the same thing - logging some stuff, before navigating. The only way I found to do it is to wait for the return value of the XHR request.
Even though it's synchronous, the execution of the code forks in background and doesn't actually block the browser. You have to get the return value to be able to halt the script to upload the data.
Mind that I used jQuery for this, but it applies to native JS (I think.. :))
/* some code above */
var request = {
async:false,
cache: false,
url: this.serviceURL,
type: 'POST',
data: {...},
success: function(data) {}
};
try {
var asd = $j.ajax(request); // do the request and wait
}
catch (e) {}
/* some code below */
I hope this helps.

How would we use Javascript to create a real-time feed?

I'm currently programming in JSP and Javascript. (I am by no means an expert in either). Right now, what I want is for a Javascript function to be called repeatedly and one of the variables to be queried from the database repeatedly (it is the date that the page was last modified). If this variable is greater than when the page was loaded, I want the page to refresh.
What I have so far:
...
<body onload="Javascript:refreshMethod()">
<script type="text/JavaScript">
<!--
function refreshMethod()
{
var interval = setInterval("timedRefresh()", 10000);
}
function timedRefresh() {
var currenttime = '<%=currentTime%>';
var feedlastmodified = '<%=EventManager.getFeedLastModified(eventID)%>';
var currenttimeint = parseInt(currenttime);
var feedlastmodifiedint = parseInt(feedlastmodified);
if(feedlastmodifiedint > currenttimeint)
{
alert(feedlastmodifiedint);
setTimeout("location.reload(true);",timeoutPeriod);
}
if(feedlastmodifiedint < currenttimeint)
{
alert(feedlastmodifiedint + " : " + currenttimeint);
}
}
// -->
</script>
The problem is that everytime the timedRefresh runs, the feedlastModifiedInt never changes (even if it has been changed).
Any help would be appreciated,
Thanks.
The JSP code within the <% ... %> tags runs only once, on the server-side, when the page is loaded. If you look at the source of the page in the browser, you will find that these values have already been placed within the JavaScript code, and thus they will not change during each timer interval.
To update the data as you are expecting, you can use AJAX. You can find plenty of tutorials online.
JSP and JavaScript doesn't run in sync as you seem to expect from the coding. JSP runs at webserver, produces a bunch of characters which should continue as HTML/CSS/JS and the webserver sends it as a HTTP response to the webbrowser as response to a HTTP request initiated by the webbrowser. Finally HTML/CSS/JS runs at the webbrowser.
If you rightclick the page in webbrowser and choose View Source, you'll probably understand what I mean. There's no single line of Java/JSP code. It has already done its job of generating the HTML/CSS/JS. The only communication way between Java/JSP and JavaScript is HTTP.
You need to move this job to some servlet in the server side and let JS invoke this asynchronously ("in the background"). This is also known as "Ajax". Here's a kickoff example with a little help of jQuery.
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
var refreshInterval = setInterval(function() {
$.getJSON('refreshServlet', function(refresh) {
if (refresh) {
clearInterval(refreshInterval);
location.reload(true);
}
});
}, 10000);
});
</script>
Where the doGet() method of the servlet which is mapped on an url-pattern of /refreshServlet roughly look like this:
response.setContentType("application/json");
if (EventManager.getFeedLastModified(eventID) > currentTime) {
response.getWriter().write("true");
} else {
response.getWriter().write("false");
}
See also:
Communication between Java/JSP/JSF and JavaScript

$(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