jQuery: assistance with updating div content onchange - javascript

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

Related

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);
});

Sending jQuery ajax request on keyboard input

I'm sending an ajax request to the server on user's input to an <input> element, like this:
$('#my-input').bind("input", function(event){
// here's the ajax request
});
What bothers me is that it send unnecessarily many requests on every user's keyup, meaning that if the user types very fast, there are many unnecessary requests. So I get the idea that there should be a certain delay/timeout, which waits a certain time (50 miliseconds?) for the user to stop typing before sending the ajax request. That would be one problem solved.
But what about cases when the first ajax request haven't been completed before sending another request? (Typing 60 ms / char while ajax request taking 300 ms).
What is the best way to solve this problem (both idea- and code-based)?
You can use throttle function in underscore library. As its documentation says:
Creates and returns a new, throttled version of the passed function, that, when invoked repeatedly, will only actually call the original function at most once per every wait milliseconds. Useful for rate-limiting events that occur faster than you can keep up with.
Even if you don't want to introduce a new library, you can still get idea about how this function works from its source code. In fact, a simple version of throttle function could be:
function throttle(func, delay) {
var timeout = null;
return function() {
var that = this, args = arguments;
clearTimeout(timer);
timeout = setTimeout(function() {
func.apply(that, args);
}, delay);
};
}
This jQuery throttle-debounce plugin is also helpful. Especially, the debounce function seems more suitable to your needs than throttle function according to its author:
Debouncing can be especially useful for rate limiting execution of handlers on events that will trigger AJAX requests
You could just use the setTimeout function. Every so often, see if the text hasn't changed, and if it hasn't, then process accordingly.
setTimeout(function() {
// Do something after 1 second
}, 1000);
You can set async: false in your ajax request so it will process second ajax call only after completion of first ajax request.
I'd go with #HuiZeng's answer, but just in case you want a slightly modified version.
Steps
Listen to keydown using a setTimeout that you can clear.
When it fires, check if you have a previous request in queue, if so abort it and fire a new one
Example:
var inputTimer = 0, req;
function onInput(e){
clearTimeout(inputTImer);
inputTimer = setTimeout( function(){
// You have access to e here
// Cancel any previous requests
req && req.abort();
req = $.ajax({/*...Do your magic here :)*/})
}, 100)
}

Refresh Page attributes using Ajax

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);

How do I send an AJAX request upon page unload / leaving?

window.onbeforeunload = function() {
return $j.ajax({
url: "/view/action?&recent_tracking_id=" + $recent_tracking_id + "&time_on_page=" + getSeconds()
});
}
this what I have, but it returns an alert with [object Object]
how do I just execute the AJAX?
note: when I just don't return anything, the server doesn't show that it is receiving the ajax request.
You don't need to return anything, just fire the ajax call.
window.onbeforeunload = function(e) {
e.preventDefault();
$j.ajax({ url: "/view/action?&recent_tracking_id=" + $recent_tracking_id + &time_on_page=" + getSeconds()
});
}
If you are using jQuery, you can try binding to the .unload() event instead.
onbeforeunload allows you to return a string, which is shown in the 'Do you want to leave' confirmation. If you return nothing, the page is exited as normal. In your case, you return the jqXHR object that is returned by the JQuery ajax method.
You should just execute the Ajax call and return nothing.
Why are you returning the reference of function to global pool? It should be like this:
window.onbeforeunload = function() {
$j.ajax({
url: "/view/action?&recent_tracking_id=" + $recent_tracking_id + "&time_on_page=" + getSeconds()
});
}
To the best of my understanding, the onbeforeunload function will only return an alert. This was done to prevent the annoying popups of a few years back.
I was building a chat client a while back and the only way i could figure out to do something like this is to do a setInterval function that updated a timestamp, then checked for timed out users and removed them. That way users that didnt "check in" within a certain interval would be removed from the room by other users still logged in.
Not pretty, or ideal, but did the trick.
Doing standard ajax calls in a page unload handler is being actively disabled by browsers, because waiting for it to complete delays the next thing happening in the window (for instance, loading a new page).
In the rare case when you need to send information as the user is navigating away from the page (as Aaron says, avoid this where possibl), you can do it with sendBeacon. sendBeacon lets you send data to your server without holding up the page you're doing it in:
window.addEventListener("unload", function() {
navigator.sendBeacon("/log", yourDataHere);
});
The browser will send the data without preventing / delaying whatever is happening in the window (closing it, moving to a new paeg, etc.).
Note that the unload event may not be reliable, particularly on mobile devices. You might combine the above with sending a beacon on visibilitychange as well.

Stop javascript function if not finished within 5 seconds (jquery)

I currently use several APIs to pull data from other sites. However, sometimes the APIs are incredibly slow (especially Twitter) and the script will continue to run perpetually because Twitter never responds.
My question is how can I tell the function to stop IF and ONLY IF it hasn't completed in x number of seconds? I'm assuming this has something to do with setTimeout(), but I can't figure it out.
Here's some example code from the Yahoo Weather API:
<script type="text/javascript">
$(function() {
$.simpleWeather({
zipcode: '<?= $property_zip ?>',
unit: 'f',
success: function(weather) {
//success
},
error: function(error) {
$("#weathercontent").html('<p>'+error+'</p>');
}
});
});
</script>
Thanks,
Phil
You could set a global timeout for all jQuery AJAX requests to 5 seconds. I believe this also covers JSONP requests since jQuery 1.5, but it may be worth investigating.
You could setup a single handler where timeout is set. It could be based on the URL of the outgoing request. So maybe for all calls to Yahoo, or Flickr, or Twitter, you can set a timeout. The pre-filter below would run before each AJAX request is sent, and gets a chance to modify the request fully before it is sent.
jQuery.ajaxPrefilter(function(options) {
if (options.url is not going to my server) { // pseudocode :)
options.timeout = 5000;
}
});
If you don't want a global handler, then set the timeout property in each $.ajax({ .. }) call you are making. This could be problematic for 3rd-party plugins such as simpleWeather which you'll have to modify the source for if setting the timeout explicitly.
Do you mean how can you cancel the ajax request if the server response is slow? I believe it's myAjaxRequest.abort(). This is not that same thing as stopping a function mid-execution. I'm not sure there's a way to do that.

Categories

Resources