How to load a part of page every 30 seconds [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
jQuery Ajax request every 30 seconds
I know we can load a part of page on some event. I also know we can load whole web page every specified time, but I wanted to know how to load a part of page every 30 seconds.

function refreshPage() {
$.ajax({
url: 'ajax/test.html',
dataType: 'html',
success: function(data) {
$('.result').html(data);
},
complete: function() {
window.setTimeout(refreshPage, 30000);
}
});
}
window.setTimeout(refreshPage, 30000);
Using setTimeout has the advantage that if the connection hangs for some time you will not get tons of pending requests since a new one will only be sent after the previous one finished.

function load_content(){
setTimeout(function(){
$.ajax({
url: 'ajax/example.html',
dataType: 'html',
success: function(data) {
$('.result').html(data);
load_content();
}
});dataType: 'html',
},30000);
}
load_content();

jQuery has already a build in functionality to replace a element's content by a remote file, called load(). With load() you can use this oneliner:
window.setTimeout($('#refresh').load('/remote/content.html'), 30000);
#refresh is the id of the element to refresh, /remote/content.html is the remote content.

$(function() {
setInterval(function() {
getData(); // call to function
}, 30000 ); // 30 seconds
});
// define your function here
function getData() {
var url ="/mypage.php?type=load_data";
var httpobj = $.ajax({url:url,async:false}); // send request
var response = httpobj.responseText.trim(); //get response
$('#myDiv').html(response); // display data
}

If you are using jQuery you can use the load() method
setInterval(function(){
$('#some-kinda-container').load('/some/kinda/url.html #bit-you-need');
}, 30000);

Related

AJAX runs onload and at set intervals

I am currently trying to get my AJAX to work when the document loads and runs every 20 seconds. How do i go about doing this? I have got it to work for every 20 seconds but cant get it to work when the document loads. Any help would be brilliant.
<script type="text/javascript" language="javascript">
window.setInterval(function(){
var jobid = $('#jobid').text();
var filename = $('#filename').text();
$.ajax({
url: "../progress_bar.php",
type:'POST',
data: {"value1": jobid, "value2": filename},
dataType: 'json',
success: function(responce){
$("#progress").html(responce);
} // End of success function of ajax form
}); // End of ajax call
}, 20000);
</script>
Thanks
For ajax requests one should always use recursive timeouts instead of intervals ( cause the request may last longer then the interval, so there are multiple requests done at a time ) , which also solves the main problem:
//may wrap the whole thing into an onload listener
(function update(){
$.ajax({
url: "../progress_bar.php",
type:'POST',
data: {"value1": jobid, "value2": filename},
dataType: 'json',
success: function(responce){
$("#progress").html(responce);
//update again in 20secs:
setTimeout(update, 20000);
}
});
})(); //start immeadiately
A small demo:
console.log("load");
(function next(){
console.log("run");
setTimeout( next, 1000);
})()

ajax jquery update page without refreshing

I currently have the below function which updates the data in a div when the page is refreshed and this works fine however i want to edit the function to make it constantly update say every 2 seconds without having to refresh the page. How would i go about doing this?
<script>
$(document).ready(function ajaxLoop() {
//-----------------------------------------------------------------------
// Send a http request with AJAX Jquery
//-----------------------------------------------------------------------
$.ajax({
url: 'getOrderStatus.php', // Url of Php file to run sql
data: "",
dataType: 'json', //data format
success: function ajaxLoop(data) //on reciept of reply
{
var OrdersSubmitted = data[0].SUBMITTED; //get Orders Submitted Count
var OrdersFulfilled = data[0].FULFILLED; //get Orders Fulfilled count
//--------------------------------------------------------------------
// 3) Update html content
//--------------------------------------------------------------------
$('#OrdersSubmitted').html("SUBMITTED:" + OrdersSubmitted);
$('#OrdersFulfilled').html("FULFILLED:" + OrdersFulfilled); //Set output html divs
}
});
});
</script>
You can chain setTimeout calls to achieve this:
$(document).ready(function() {
function updateOrders() {
$.ajax({
url: 'getOrderStatus.php',
dataType: 'json',
success: function ajaxLoop(data) {
var OrdersSubmitted = data[0].SUBMITTED;
var OrdersFulfilled = data[0].FULFILLED;
$('#OrdersSubmitted').html("SUBMITTED:"+ OrdersSubmitted);
$('#OrdersFulfilled').html("FULFILLED:"+ OrdersFulfilled);
setTimeout(updateOrders, 2000);
}
});
});
The alternative is setInterval(), however if the requests slow down this can lead to calls being queued, which will eventually lead to memory issues.
You need to add a repeating event to call your updateOrders function. Like:
function startUpdateOrdersTimes() {
setInterval(function() {
updateOrders();
}, 2000);
//Call now (otherwise waits for first call)
updateOrders();
}
Using "window.setInterval" (https://developer.mozilla.org/en/docs/Web/API/window.setInterval) you can repeatedly execute a function at a specified time interval.
function SomeFunction()
{
$.ajax({...});
}
window.setInterval(SomeFunction,2000);
This would execute SomeFunction every 2 seconds
Hope this helps
timerupdateorders = setInterval(function() {
ajaxLoop();
}, 2000);
You may use
clearInterval(timerupdateorders);
to end the timer

How to stop setInterval();? [duplicate]

This question already has answers here:
How to stop "setInterval" [duplicate]
(4 answers)
Closed 8 years ago.
I have like...
<div id="div"></div>
<script src="jquery.js"></script>
<script src="updater.js"></script>
The updater I want to get data from my .php file, so probably something like...
setInterval(function() {
$.ajax({
type: "GET",
url: "test.php",
success: function(html) {
// html is a string of all output of the server script.
$("#div").html(html);
}
});
}, 5000);
Then, obviously enough the test.php's page will result.
But, I want to STOP the setInterval(); WHEN someone clicks on a comment button (textarea). I'm aware, there's some on here; but they're not working?
Window.clearInterval, It accepts an intervalID is the identifier of the repeated action you want to cancel. This ID is returned from setInterval().
Example
var interVal = setInterval(function() {
$.ajax({
type: "GET",
url: "test.php",
success: function(html) {
// html is a string of all output of the server script.
$("#div").html(html);
}
});
}, 5000);
clearInterval(interVal); //Call the method when you want to clear it.
The setInterval function will return an integer which identifies that interval. Save that integer for later use, and when you want to clear the interval pass it into clearInterval as an argument.
E.g.:
var myInterval = setInterval(function() {
$.ajax({
type: "GET",
url: "test.php",
success: function(html) {
// html is a string of all output of the server script.
$("#div").html(html);
}
});
}, 5000);
And then when you want to cancel it:
clearInterval(myInterval);
Reference:
http://www.w3schools.com/jsref/met_win_clearinterval.asp
You can use clearInterval. It takes the Id of interval & clears it.
Get your setInterval in a variable.
var interval = setInterval(function(){...},time);
After clicking on button just do
clearInterval(interval);
DEMO

AJAX doesn't automatically update before button is pressed

I'm making a conversation system where 2 people can chat with each other. I've made an AJAX function which updates the DIV box containing the messages every 2 seconds.
This is working as intended, after a user have written a message. Why isn't the AJAX call being run right away?
// SET AUTORUN updateMessages() EVERY 2 SECONDS
$(document).ready(function() {
var interval
window.onload = function(){
interval = setInterval('updateMessages()', 2000);
};
});
// UPDATE #mail_container_conversation
function updateMessages() {
$.ajax({
type: "POST",
url: "<?php echo site_url(); ?>mail/ajaxupdate/<?php echo $user; ?>",
data: dataString,
 
success: function(data){
$("#mail_container_conversation").html(data);
}
});
}
// SEND NEW MESSAGE
$(function(){
$("#mail_send").submit(function(){
dataString = $("#mail_send").serialize();
 
$.ajax({
type: "POST",
url: "<?php echo site_url(); ?>mail/send",
data: dataString,
 
success: function(data){
updateMessages();
$(".mail_conversation_answer_input").val('');
}
 
});
 
return false;
});
});
You should provide functions instead of strings to setTimeout/setInterval functions. And also there's no need for you to set interval on window load event. You can just keep it as part of DOM ready:
$(function() {
updateMessages(); // don't wait 2 seconds for first update
setInterval(updateMessages, 2000); // update every 2 seconds
});
Everything else seems to should work as expected as long as your posback work when no data is being received (ref dataString).
I hope you do realise that you're using implied globals and understand why that may be a big problem (ref dataString again).
How I would rewrite your code
I would rewrite your whole code into the following that removes implied global variable dataString, doesn't pollute global scope with additional functions and uses setTimeout instead of interval which may in some cases be problematic (although in your case since it' only runs every 2 seconds it shouldn't be a problem if there's no additional very complex client-side script execution)
I've kept everything within function closure local scope:
$(function() {
var timeout = null;
var form = $("#mail_send").submit(function(evt){
evt.preventDefault();
$(".mail_conversation_answer_input", form).val("");
updateMessages();
});
var updateMessages = function() {
// we don'w want submit to interfere with auto-updates
clearTimeout(timeout);
$.ajax({
type: "POST",
url: "<?php echo site_url(); ?>mail/send",
data: form.serialize(),
success: function(data){
$("#mail_container_conversation").html(data);
timeout = setTimeout(updateMessages, 2000);
}
});
};
// start updating
updateMessages();
});
This code requires your server side (processing on /mail/send) to understand that when nothing is being posted (no data) that it doesn't add empty line in the conversation but rather knows that this is just an update call. This functionality now uses only one server-side URL and not two of them. If you'd still require two, then this code should do the trick:
$(function() {
var timeout = null;
var url = {
update: "<?php echo site_url();?>mail/ajaxupdate/<?php echo $user;?>",
submit: "<?php echo site_url();?>mail/send",
use: "update"
};
var form = $("#mail_send").submit(function(evt){
evt.preventDefault();
url.use = "submit";
$(".mail_conversation_answer_input", form).val("");
updateMessages();
});
var updateMessages = function() {
// we don'w want submit to interfere with auto-updates
clearTimeout(timeout);
$.ajax({
type: "POST",
url: url[url.use],
data: form.serialize(),
success: function(data){
$("#mail_container_conversation").html(data);
url.use = "update";
timeout = setTimeout(updateMessages, 2000);
}
});
};
// start updating
updateMessages();
});
If the rest of your code work, the problem probably is withing this code:
$(document).ready(function() {
var interval
window.onload = function(){
interval = setInterval('updateMessages()', 2000);
};
});
There is no need to attach it to window.onload, since you already wrapped it in a DOM-ready callback.
Remove the single-quotes and the parenthesis from within your call to setInterval
The DOM-ready callback can be shorten, by just passing a function to the jQuery-method.
Try this instead:
$(function () {
setInterval(updateMessages, 2000);
});
Further improvements - Avoid intervals with AJAX:
When dealing with AJAX, you should avoid using intervals, as you may end up stacking calls to the server, if the server takes more than two seconds to respond. setInterval will not care if your server had time to respond or not, it will keep calling it every 2 seconds no matter what.
I suggest that you use a timeout instead, and start a new timeout in the complete-callback of the Ajax-call.
In your case, it could look something like this:
$(function () {
// Make the first call immediately when the DOM is ready
updateMessage();
});
function updateMessages() {
$.ajax({
type: "POST",
url: "<?php echo site_url(); ?>mail/ajaxupdate/<?php echo $user; ?>",
data: dataString,
success: function(data){
$("#mail_container_conversation").html(data);
// Make a new call, 2 seconds after you've
// received a successful respose
setTimeout(updateMessages, 2000);
}
});
}
The problem is that updateMessages() tries to send datastring to the server, but this doesn't get filled in until the .submit() function runs.
I don't know what you should put in there, since I don't know what the mail/ajaxupdate script expects. If this is called when nothing happens, I suspect no form data is needed at all, so you can give an empty string.
I'll bet if you checked the Javascript console you'd see some error messages about trying to serialize undefined.
give a try with
$(document).ready(function() {
setInterval('updateMessages()', 2000);
});
You don't need the window.onload in your document ready call.
$(document).ready(function() {
setInterval('updateMessages()', 2000);
});
That should be enough to get it started.
As it is now, once the DOM is ready, you're then asking it to wait for the window to load.. but by that point it's already loaded, so nothing happens.

jquery ajax failed request not triggering complete or error handler

I'm making an ajax call like this:
var requestData = function() {
$.ajax({
dataType: 'jsonp',
jsonp: 'js',
url: "http://someServer",
success: function (data) {
// do stuff with data
},
complete : function(data) {
// try again in 5 seconds
setTimeout(requestData, 5000);
}
});
};
All is well and good, and it works, EXCEPT: the server is a bit flaky, and from time to time, it fails to return a response. That's fine, but when that happens, the complete handler never fires. I've also tried using an error handler. Is there something else I can do? I've thought about using setInterval, but I'd really rather it do the next one after this one, not at a set time where they might pile up....
UPDATE: when the server fails, I get "Failed to load resource" in chrome's console.
The problem is that JSONP works by inserting a script tag into the DOM, rather than by XMLHTTPRequest. script tags have no onerror property, so you can't test for success by conventional methods. The only way to do it is via a timeout.
Something like this might work:
var requestComplete = {};
var requestData = function() {
var now = (new Date()).getTime();
requestComplete[now] = false;
$.ajax({
dataType: 'jsonp',
jsonp: 'js',
url: "http://someServer",
success: function (data) {
requestComplete[now] = true;
// do stuff with data
}
});
setTimeout(function() {
if (!requestComplete[now]) {
setTimeout(requestData, 5000); // try again in 5 seconds
}
}, 5000); // give the JSONP request 5 seconds to work
};

Categories

Resources