ajax jquery update page without refreshing - javascript

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

Related

How to call this function automatically

Im using the following function to call an ajax request, and fill certain corresponding divs with the response:
$( function() {
$(document).ready(function() {
var postData = "";
$.ajax( {
url : \'functions/ajax_api.php?\',
type : \'post\',
data : postData,
success : function( resp ) {
$(\'#id1\').html($(\'#id1\' , resp).html());
$(\'#id2\').html($(\'#id2\' , resp).html());
}
});
return false;
});
});
The function works fine. My question is how can I call it automatically every few seconds?
I tried using window.setTimeout(function, 3000) but I couldnt set it up correctly.
use setInterval(); instead of .setTimeout()
Let me help you a little bit with that
var interval , setItinterval; // just a variables you can change names
interval = function(){
// ajax code here
}
to run it .. use:
setItinterval = setInterval(interval , 3000);
to stop it .. use
clearInterval(setItinterval);
Make sure to read setInterval for more information.
For Complete answer and Last thing I want to say when using setInterval(); Its better to use visibilitychange to avoid server error , server load or something like that
document.addEventListener('visibilitychange',function(){
if(document.visibilityState == 'visible'){
// user view the page
}else{
// user not see the page
}
});
You can use setTimeout() or setInterval, but setInterval may result in multiple simultaneous ajax calls if those calls take too long to respond. That isn't a problem if you call setTimeout() in the ajax success callback.
To use setTimeout(), first wrap your ajax call in a function. You can then add a call to setTimeout() to the ajax success callback. You also need to call the function once to start of the looping.
$(function() {
function postData() {
var postData = "";
$.ajax({
url: 'functions/ajax_api.php?',
type: 'post',
data: postData,
success: function(resp) {
$('#id1').html($('#id1', resp).html());
$('#id2').html($('#id2', resp).html());
// Call postData again after 5 seconds.
setTimeout(function() { postData(); }, 5000);
}
});
}
// Call postDate the first time to start it off.
postData();
});
Note: With the call to setTimeout in the success callback, the cycle will break if an ajax call fails. You may want that, but if you want it to act more like setInterval, you can place the call to setTimeout in the complete callback.
Here's some example code that will do it (note that it runs the function when the document loads, and then starts the interval). You can always use clearInterval(refresh_interval) if you need to stop it.
var refresh_interval;
function update_content() {
$.ajax({
url : \'functions/ajax_api.php?\',
type : \'post\',
data : postData,
success : function( resp ) {
$(\'#id1\').html($(\'#id1\' , resp).html());
$(\'#id2\').html($(\'#id2\' , resp).html());
}
});
}
$(document).ready(function() {
update_content();
setInterval(update_content, 3000);
}
The relevant documentation for using intervals is here: https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval
Though you may want to look into Server Sent Events, it's probably a better solution for what you want.

auto refresh div every x seconds and stop to successsful load

I need to create a div that will auto refresh every 10 seconds, and stop when it successfully loads. I created this jQuery script:
<script type="text/javascript">
$(document).ready(function(){
var j = jQuery.noConflict();
j(document).ready(function()
{
j(".refresh").everyTime(1000,function(i){
j.ajax({
url: "pin.php",
cache: false,
success: function(html){
j(".refresh").html(html);
}
})
})
});
j('.refresh');
});
</script>
It works but the refresh continues every 10 seconds. I need it to stop if pin.php returns a numeric output.
How can I edit it to stop refresh if pin.php returns a numeric output?
From the documentation over at http://www.jquery-plugins.info/jquery-timers-00013992.htm, the function you need is probably stopTime. Although I haven't tested it, the following in your success should work:
success: function(html) {
if (j.isNumeric(html)) {
j(".refresh").stopTime();
} else {
j(".refresh").html(html);
}
}
Try it with an interval like this, it fires till the loaded call is done then it stops the interval and ajaxcal
$(document).ready(function(){
var j = jQuery.noConflict();
jRefresh();
var jRefresh = setInterval(function(){
ajaxCall()
}, 1000);
function ajaxCall() {
j.ajax({
url: "pin.php",
cache: false,
success: function(html){
if (j.isNumeric(html)) {
myStopFunction();
}
}
})
}
function myStopFunction() {
clearInterval(jRefresh);
}
});
first of all you do not need to call $(document).ready() twice. To aviod conflicts you can write code like this :
jQuery(document).ready(function($){
// Your code here
});
Note the $ parameter
Second, I guess it is unuseful to use everytime ( looks like is a plugin and is not a good idea to load a lot of code since you have good alternatives for your needs ) when you can simply call setInterval;
According to your needs and following what i said above, the code should looks like :
jQuery(document).ready(function($){
var interval_time = 10000;
var interval = null;
var $wrapper = $('.refresh');
interval = setInterval(function(){
$.ajax({
url : 'pin.php',
cache : false,
success : function( html ){
if( $.isNumeric( html ) ){
clearInterval( interval );
}
$wrapper.html( html );
}
})
}, interval_time);
});
You can modify your code something like this:
var temp = setInterval(1000,function(i){
j.ajax({
url: "pin.php",
cache: false,
success: function(html){
if(isNaN(html))
j(".refresh").html(html);
}else{temp.clearInterval();}
})
})
You said, "I need it to stop if pin.php returns a numeric output".
if .refresh html contain number than it stop to call ajax call otherwise it make call.
if(isNaN(j(".refresh").html()){
//put your ajax call in this block
}

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.

How do I get first value instantly if my throttle is set to 120000

So basically I wan't to get data from server at start and then update it every 2 minutes, but instead it gets first value only after 2 minutes, what can I do about this?
Here is my js markup:
var itemViewModel = {
item: ko.observable().extend({ throttle: 120000 }),
loadcontent: function (getID) {
$.ajax({
url: '/api/item/details/' + getID,
dataType: 'json',
success: function (data) {
itemViewModel.item(data);
}
});
}
};
Maybe this will help, here is a HTML markup:
<div id="item-details-content">
<input type="hidden" id="item-id" value="#id" data-bind=""/>
<div class="item-list" data-bind="init: itemPage.loadcontent(#id), with: itemPage.item">
Conditions
There need to be and initial call of loadcontent
Everything must be inside viewModel
That's not what the throttle extender (link) is meant for. Use setInterval (link) instead.
throttle is meant to handle a scenario where you may receive an arbitrary amount of events in a short timespan and you do not want to act upon every single event. E.g. you have a search field with autocomplete functionality that uses a REST-API. You do not want to call the REST-API every single time a user pushes a key. Rather, you'd like to wait a bit until the user is done typing. This is a perfect use case for throttle.
What you are looking for is a way to repeat an action on a predetermined interval. JavaScript has a builtin function just for that and it's called setInterval.
var itemViewModel = {
item: ko.observable().extend({ throttle: 120000 }),
loadcontent: function (getID) {
var loadData = function()
{
$.ajax({
url: '/api/item/details/' + getID,
dataType: 'json',
success: function (data) {
itemViewModel.item(data);
}
});
}
loadData(); // initial call
setInterval(loadData, 120000); // repeat every 2 minutes
}
};
Throttle's intended use is to make sure the function does not execute more then once every x seconds. As Martin said, setInterval would be better in this situation
var interval = setInterval(function() {
ko.observable();
}, 120000);
ko.observable();

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

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

Categories

Resources