Refresh Page attributes using Ajax - javascript

I have a scenario where I need to make a call to Java method and check whether a call is finished or not. If it's finished, I need to display a message. This can be done easily using ajax function. but the problem is, I will be setting some request parameters in this method, will they get reflected after ajax.
One more doubt is, how can I control the polling interval for this
<script type="text/javascript">
setTimeout(function () {
location.reload();
}, 60 * 1000);
</script>
I want to execute this refresh script only if
<s:if test="#request['Isam2Asam'] != null">
else the page should never be reloaded.

Ajax can easily send request parameters.
You are looking for setInterval though - jQuery version:
var tId = setInterval(function() {
$.get("somejsp?parm="+someParm,function(data) {
if (data=="done") {
clearInterval(tId); // stop polling
$("#message").html("Done"); // update a div id="message"
}
});
},60000);

Related

Automatically refreshing page data with ajax

I have a page with a list of items for the user to complete in a queue. Items get added into the database, and I need this list to be updated and reflect those changes on a regular basis (perhaps every minute).
I don't want to add a meta refresh to the page, because I want to avoid reloading the page. I already have a function that updates the list via ajax, so I'd like to call this function every minute.
Once the page is initially loaded, how can I repeatedly call this function without doing a blocking javascript loop? Is there a way to pause the setInterval or something to allow the rest of the queue pool to execute?
I'm worried about this happening:
$('document').ready(function () {
setInterval( function() {
updateList();
}, 60000);
}
A while(true) loop will indeed block the execution of all other scripts. setInterval will not.
The ideal solution would be a web socket like socket.io. With this, you could have something as simple as
socket.on("add", function (msg) {
addItem(msg);
}).on("removeItem", function (msg) {
removeItem(msg);
})
Then, on your server, you could simply socket.emit("messageType", msg);. This would prevent you from having to constantly poll the server with AJAX.
However, if that is not possible, you can fix your code with
$(document).ready(function () {
var updateInterval = setInterval(updateList, 60000);
// to clear interval: clearInterval(updateInterval);
})
where updateList is your function to poll the server via AJAX and append whatever tasks are received to the page.
You can use any of the following two:
setTimeout(expression, timeout); which executes the code/function once after the timeout. It is non blocking so you don't have to put it in a loop. You can call itself to make it execute infinitely.
function updateFunction() {
setTimeout(function() {
//update the page here
updateFunction();
}, 1000);
}
Or you can use setInterval(expression, timeout); which executes the code/function in intervals, with the length of the timeout between them.
setInterval(function() {
//update the page here
}, 1000);
Summing up from the comments:
You should get rid of while(true), it is blocking the rest of the code.
The setInterval() will be executed every 1min. anyway.
Note that after removing the while, the setInterval() will not block the rest of the code.

How to make casperJS wait until .change() event is finished?

I am triggering a change event in my casperJS script which triggers an AJAX request like such:
casper.evaluate(function(i) {
$("form:eq(2) select option:eq(" + i + ")").attr("selected", "selected").change();
},i);
How can I make casperJS wait until the underlying AJAX request has been finished? Already tried to look at the docs but I am more or less stuck. Can anyone guide me into the right direction?
You can always do this in a static way using casper.wait.
casper.thenEvaluate(function(i) {
// change()
},i).wait(5000).then(function(){
// further processing
});
And hope that the request is done in 5 seconds, but maybe you lose some time waiting when the request is done much sooner than 5 seconds. The problem is that as soon as the request is finished doesn't mean that the page is ready/changed.
Another possibility would be to wait for the request to finish, but for this to work you will need to register for the success event of the request somehow. Most of the time you don't have access to this from the global scope. If you do then you can use
casper.thenEvaluate(function(i) {
window._someUniqueVariable = false;
registerSuccessEvent(function(data){
window._someUniqueVariable = true;
});
},i).waitFor(function check(){
return this.evaluate(function(){
window._someUniqueVariable = true;
});
}, function(){
// further processing
});
A more Casper-way of doing that would be to use casper.waitForResource, but then you would need to know the url beforehand or at least able to deduce it from the page.
In the general case, when the request comes back it does something to your page. So you should be able to waitForSelector with a new element or waitForSelectorTextChange or waitUntilVisible etc.
you probably missed waitForResource
from the docs: http://casperjs.readthedocs.org/en/latest/modules/casper.html#waitforresource
casper.waitForResource("you url here", function()
{
// place your code here
});

Periodically send ajax requests

There is a page and I want periodically to make "background" ajax requests. So the page is loaded then it should send ajax requests in a certain amount of time.
I might use cron for that. I have never use previously so I'm wondering if it would fit for that task. Is there any other more simple way?
P.S. The time delay will be about 5 minutes.
Since there is essentially an unknown delay between the time you send out an AJAX request and the time you receive a complete response for it, an oftentimes more elegant approach is to start the next AJAX call a fixed amount of time after the prior one finishes. This way, you can also ensure that your calls don't overlap.
var set_delay = 5000,
callout = function () {
$.ajax({
/* blah */
})
.done(function (response) {
// update the page
})
.always(function () {
setTimeout(callout, set_delay);
});
};
// initial call
callout();
Cron is run on the serverside and you are using HTML and AJAX, so you should solve this issue in Javascript :-)
By using something like setInterval you can keep executing a function, your case might be something like polling a url via AJAX:
function updatePage(){
// perform AJAX request
}
setInterval(updatePage, 5000);
Depending on your rails version you may be able to use periodically_call_remote, otherwise you'll need the jquery alternative that #Bitterzoet described.
More info in this question.
You can send ajax request in four second like this:
setInterval(get_news, 4000);
function get_news(){
$.ajax('/dashboards/get_news', {
type: 'POST',
success: function(result) {
if(result > 0){
$('#div_1').text("See "+result+" new messages");
$('#div_1').show();
}
else{
$('#div_1').css('display', 'none');
}
},
error: function() {
// alert("Error")
}
});
}
Are you using jquery? If so, you can implement this method:
// first, you need asing a callback timer
var timeout = 300; //milliseconds
// this method contain your ajax request
function ajaxRequest() { //function to ajax request
$.ajax({
url: "/url/to/request/"
}).done(function(data) {
alert("response is: " + data);
});
}
$(document).on("ready", function(){
//this method will be called every 300 milliseconds
setInterval(ajaxRequest, timeout);
});

time an ajax request

Is there any way to time how long a jquery ajax request has been going on? sometimes searches take too long and it would be nice to add a jquery abort() button if the search takes over, say, 5 seconds. Any way I can do this!
On the other end of the ajax request is a php file that makes a postgresql request.
Much thanks for any ideas!
Take a look at the timeout option (http://api.jquery.com/jQuery.ajax/). You can set it on a particular call, or globally with $.ajaxSetup().
To have the abort button appear after 5 seconds, add a setTimeout function after your call to send. Once the AJAX command is complete, you can add code to clear the timeout and remove the abort button if it exists.
var timeOutID = 0;
$.ajax({
url: 'ajax/test.html',
success: function(data) {
clearTimeOut(timeOutID);
// Remove the abort button if it exists.
}
});
timeOutID = setTimeout(function() {
// Add the abort button here.
}, 5000);
This way the abort button will never appear if AJAX returns quick enough.
Usually, I'll set a timeout once the request is sent that will trigger after 10 seconds or so and then fallback on something else to make sure it still happens (for example, form submission).
So set a variable to false, var failed = false; and do the request
At the same time that the request starts, set a timeout:
setTimeout(function() {
failed = true;
$("#form").submit();
return false;
}, 10000);
In the return function of the ajax call, check to see if the failed variable has been set to true, and if it has, don't actually do whatever it was originally trying, otherwise it could mess something up, or confuse the user if something else is happening (since these things usually happen on slower internet connections, if the next step appears while a new page is loading, they might try to interact and then the page will change).
$.post("ajaxcall.php", {'etc': "etc"},
function(returned) {
if (failed != true) {
//do whatever with returned variable
}
});
var timer = 0,
XHR = $.ajax({
url: 'ajax/mypage.html',
beforeSend: function() {
timer=setTimeout(showAbort, 5000);
}
});
function showAbort() {
$('<input type="button" value="Abort" id="abort_button"/>').appendTo('#some_parent');
$('#abort_button').on('click', function() {
XHR.abort(); //abort the Ajax call
});
}
XHR.always(function() { //fires on both fail and done
clearTimeout(timer);
if ($('#abort_button').length) {
$('#abort_button').remove(); //remove button if exists
}
});

jQuery: assistance with updating div content onchange

I have a div the contents of which constantly changes based on a server side process. Currently I use jQuery load to poll the server every 3 seconds to get any updates.
This is what I have:
function poll() {
reloadPage();
setTimeout("poll();", 3000);
}
function reloadPage() {
$("#mydiv").load(location.href + " #mydiv>*", "");
}
This works well in firefox but in IE, the load doesn't update the div, probably due to a caching issue. Is there a better way to do what I'm trying to do other than polling periodically?
You need to change the URL for each request to prevent IE from caching the response.
For example:
function poll() {
reloadPage();
setTimeout(poll, 3000);
}
function reloadPage() {
$("#mydiv").load(location.href + "?Timestamp=" + new Date() + " #mydiv>*", "");
}
Also, you shouldn't pass a string to setTimeout.
jQuery's ajax has a bunch of default settings, one of which controls caching. If you set that to false it will append a timestamp to the ajax call to prevent caching.
http://api.jquery.com/jQuery.ajax/
Is there a better way to do what I'm trying to do other than polling periodically?
Since HTTP is a stateless protocol, no. You have to poll to see what's going on on the server.
But there is a better way to implement the polling:
setInterval(function () {
$("#mydiv").load(location.href + " #mydiv>*", {Timestamp: new Date()});
}, 3000);
Notes:
define an Interval instead of the Timeout,
pass an actual function to setInterval, not a string
use the data parameter of load() to pass in a cache breaker

Categories

Resources