Javascript: setInterval function not working - javascript

I have the following piece of code. Interval is set to 10sec.
(function($){
$(document).ready(function() {
disp_log();
setInterval(function () {
disp_log();
}, 10 * 1000);
function disp_log() {
$.ajax({
"type" : "GET",
"url" : "/get_log/",
"dataType" : "json",
"cache" : false,
"success" : function(json) {
data=""
for(var j = 0; j < json.length; j++) {
data+="<tr><td>"+json[j]+"</td></tr>"
}
$("#log").html(data);
}
})(jQuery);
}
});
})(django.jQuery);
But refreshing dosen't happen. Can someone plz tell why?

The thing you need to do here is debug. First of all work out if you are getting any code back at all. You can do this by using....
"success" : function(json) {
console.log(json);
//or..
alert(json);
}
If they don't return anything, then your AJAX request is the problem, not your setInterval code.
However on your setInterval code, you should know that the ajax call could take any time to load, so you shouldn't just keep running it. A better way would be to use setTimeout....
setTimeout(disp_log,10*1000);
Then, inside your success function, put that same code in again...
"success" : function(json) {
setTimeout(function() {
disp_log()
},10*1000);
}
This will ensure that your code keeps running 10 seconds after the last time the data was successful. There are other issues to consider (how you keep the script running if the ajax call fails, for example) but this will ensure you don't end up getting out of sync with your server requests!

You have an error here : $.ajax does not return you something to call jQuery on. No need for that (jQuery)

Use it as below.
setInterval(disp_log, 10 * 1000);
if you function is in global then use it as
setInterval("disp_log()", 10 * 1000);
also you don't need (jQuery) after end of ajax call.
And more important you have (function($){ and $(document).ready(function() {.
You don't need it because both are same use either one.
Working Tested Code
<script type="text/javascript">
$(document).ready(function()
{
disp_log();
setInterval(disp_log, 10 * 1000);
function disp_log()
{
$.ajax({
"type" : "GET",
"url" : "/get_log/",
"dataType" : "json",
"cache" : false,
"success" : function(json)
{
var data;
for(var j = 0; j < json.length; j++)
{
data+="<tr><td>"+json[j]+"</td></tr>"
}
$("#log").html(data);
}
});
}
});
</script>

PROBLEM MAY BE OF THE BROWSER
I had a problem using this setInterval() function, but later I found it was the problem of my mozilla. When I tried to run in Chrome, it was perfect.

Related

jquery ajax while loop in odd order

I cant understand what I'm doing wrong on this one. I've got a while loop running an AJAX function to get data from a PHP file for the amount of people selected from a dropdown.
$(document).on('change', '#attendingCount', function() {
$(".person-container").html("");
var amount = $(this).val();
var i = 0;
while (i < amount) {
getPerson(i);
i++;
}
});
getPerson(0);
function getPerson(e) {
$.ajax({
type: 'post',
url: './person.php',
data: {
"amount": e
},
success: function(data) {
$(".person-container").append(data);
},
error: function() {
console.log('error');
}
});
}
When the result gets pumped out though, the order of them is completely random.
What is it exactly I'm doing wrong?!
AJAX works in an asynchronous way, not necessarily the first request you send is going to return data first, that's the problem here. Doing an AJAX call in a while loop is not the best solution.

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

Understanding how to execute Javascript functions in a certain order

I am creating a framework that allows me to start with a normal static website then if the user has Javascript enabled transforms it into a single page site that pulls in sections from the static pages as the user navigates the site.
I'm still working on the ideas but I'm struggling understanding how to execute Javascript functions in a certain order my code (edited) looks a like this:
EDIT My code in more detail:
When the loadSiteMap() function completes the variable siteMap looks like this:
{
"pageData" : [
{
"loadInTo" : "#aboutUs",
"url" : "aboutUs.html",
"urlSection" : ".sectionInner"
},
{
"loadInTo" : "#whatWeDo",
"url" : "whatWeDo.html",
"urlSection" : ".sectionInner"
},
{
"loadInTo" : "#ourValues",
"url" : "ourValues.html",
"urlSection" : ".sectionInner"
},
{
"loadInTo" : "#ourExpertise",
"url" : "ourExpertise.html",
"urlSection" : ".sectionInner"
}
]
}
The rest of my code:
function loadSiteMap() {
$('#body').empty();
$.ajaxSetup({cache : false});
$.ajax({
url: 'js/siteMap.js',
async: false,
dataType: 'json'
})
.done(function(data){
siteMap = data;
})
.fail(function(jqXHR, status){
alert('Its all gone to shit');
});
}
loadSiteMap();//So this is the first to be executed
$(function(){
function loadDataFromSiteMap() {
var toAppend = '';
var markerID = 'mark-end-of-append' + (new Date).getTime();
var loadGraphic = '<img src="images/loadGraphic.gif" alt="loading..." class="loadGraphic" />'
for(var i=0; i<siteMap.pageData.length; i++) {
var loader = siteMap.pageData[i];
toAppend += '<div id="'+ loader.loadInTo.substr(1) +'" class="sectionOuter">'+ loadGraphic +'</div>';
}
toAppend += '<div id="' + markerID + '"></div>';
$('#body').append(toAppend);
var poller = window.setInterval(function(){
var detected = document.getElementById(markerID);
if(detected){
window.clearInterval(poller);
$(detected).remove();
for(var i=0; i<siteMap.pageData.length; i++){
var loader = siteMap.pageData[i];
var dfd = $.ajax({
url: loader.url,
async: false
});
dfd.done(function(data, status, jqXHR){
var sections = $(data).find(loader.urlSection);
$(loader.loadInTo).html(sections).filter(loader.urlSection);
});
dfd.fail(function(jqXHR, status){
alert('Its all gone to shit');
});
}
}
}, 100);
}
function buildCarousel() {
$('.sectionInner').each(function(i) {
if($(this).has('.carousel').length) {
$(this).append('PrevNext');
$('.prev,.next').fadeIn('slow');
}
});
};
loadDataFromSiteMap();//This runs second then I want to execute...
buildCarousel();//Then when this is complete execute...
anotherFunction();//and so on...
Hopefully from this you can see what I am trying to achieve in terms of executing functions in order. I would like to eventually turn this concept into a jQuery plugin so I can share it. If that has any bearing on what I am trying to achieve now I welcome thoughts.
Many thanks in advance.
I think AJAX is one of the only times you'll have to worry about functions not running in a certain order in JavaScript.
The trick to asynchronous function calls like AJAX is to make use of callbacks. Put everything in the "Doc ready" section into another callable function (or just an anonymous function in the AJAX complete code), then call this function only when your AJAX call completes. The reason being that the rest of your program will go on executing while the AJAX call is being processed, so callbacks insure the AJAX call is done before continuing what you want to execute next.
If any of these other functions are asynchronous then you'll have to similarly make a callback on completion that will continue executing the rest of the functions.
As it stands, though, I see no reason every function but the AJAX one should not be called in order. At least, not without knowing how those functions work.
Edit: A code example of a callback:
$.ajax({
url: 'ajax/test.html',
success: function(data) {
//Set sitemap
(function() {
//Make the calls to your list of functions
})(); //<- Execute function right away
}
});
Also, according to here, async: false will not work on 'Cross-domain requests and dataType: "jsonp" requests', so if you're calling a different domain or using jsonp that might be the problem.

Categories

Resources