Automatically refreshing page data with ajax - javascript

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.

Related

Waiting with page load until method finished

The Javascript of my webpage is executing the code shown below when a webpage is loading. The call to get can take a couple of seconds, thus I would like to wait with loading the page until the call is finished.
Is it possible to postpone the loading of the page until the call to get finished? Or even a better way would be to show some spinning wheel (instead of a white page), so that the user is aware that some process is going on. Is this possible?
document.addEventListener("DOMContentLoaded", function(){
if (!sessionStorage.getItem("userID")) {
// Get new userID
$.get("/new_user").done(function (data) {
sessionStorage.setItem("userID", data);
});
}
});
I'm not sure if your implementation with the event listener "DOMContentLoaded" is right, I think we are missing some context here and you may be able to check session storage before this, but I will assume that part is correct and address your question about a loading spinner.
Also I wont go into detail about how to make a load spinner as there are a lot of examples out there.. but as far as having your page be a load spinner while your ajax call is running I would make the function async and set the html of the page to the loading spinner right before the call, and then after you await the call, set the data and then set the html to what you want it to be after it's done loading
document.addEventListener('DOMContentLoaded', async (event) => {
if (!sessionStorage.getItem("userID")) {
document.getElementById('container').innerHTML = '<div>loadspinnerhtml</div>';
var data = await $.get("/new_user")
sessionStorage.setItem("userID", data);
document.getElementById('container').innerHTML = '<div>theloadedhtml</div>'
}
});

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 can we set timeOut if dont know how long page loading will take

I've made script which change information from different site, its occure when i click on button, sometimes it takes 1-2 seconds to find info and display it, sometimes 10 or more seconds. i made a script which change some table rows etc in timeOut 5 seconds, how can i set timeOut if i dont know how long this search will go
$("div.dreamcast input.btn").click(function() {
$.ajax({
success: function () {
setTimeout(function() {
//i want to change results information here
$('table.itt_results tbody tr:first th:contains("etc")').hide();
},
5000 //timeout 5s
);
});
Within the succes function of the jQuery ajax call, the code gets executed as soon as the AJAX call has been successful. This way, you don't have to know how long it takes, it will always be fine.
So no need for a setTimeout here.
The success method will only be executed when you have the result so you don't need the timeout function there.
The success function will only run when the ajax function has finished successfully. There's no need to guess how long it will take.

Web page real time updates with Javascript and Ajax

What Javascript event can I use for handling real time updates on a web page with ajax?
For example; Mouse_move would create frequent ajax post requests. I need a timer event, like in each 5 seconds, update notifications, check if new notification available.
Use the setTimeout function and replace alertMsg() with your ajax function. See the tutorial here: http://www.w3schools.com/js/js_timing.asp
function timeMsg()
{
var t=setTimeout("alertMsg()",5000);
}
function alertMsg()
{
alert("Hello");
}
You don't need events at all. See setTimeout or setInterval.

Categories

Resources