jQuery Auto refresh div/span every 5 sec - javascript

i have a content to display score in html. Here is the example
<div id="homescore">0</div>
<div id="awayscore">0</div>
I want auto refresh div homescore and awayscore every 5 second without php. Is it possible

You can do it with setTimeout function.
Define a function refreshDivContent which will take your div id that needs to be refreshed.Populate div from ajax call or whatever source you are doing(I have shown an ajax example) and then call this refreshDivContent again inside setTimeout.
$(document).ready(function(){
var refreshDivContent = function(divid) {
$.ajax({
url: "path",
cache: false,
success: function(data) {
$('#' + divid).html(data);
setTimeout(function() {
refreshDivContent(divid);
}, 5000);
}
});
};
refreshDivContent('homescore'); // Use it
});

Related

Run ajax request after specific time

Hello I'm working on a website with a color slider that append a specific color page to the DOM after a slide change. I want people to still be able to go through the different slide pretty quickly and load the ajax page only if the user didn't change the slide for a specific time (for example 1000ms).
I tried setInterval, setTimeout and the ajax timeout parameter but it isn't working, it just adds requests to the call stack and after the timeout duration it appends the div 5 times.
Here's the ajax call:
$.ajax({
url: "/wp-admin/admin-ajax.php",
type:"POST",
data: {
action: "my_custom_color",
post_link: post_ID
}, success: function (response) {
$('.color').prepend(response);
},
})
I want to be able to do something like this:
colorsMonoSlider.events.on('indexChanged', () => {
setTimeout(() => {
customizedFunction()
}, 1000);
});
But without filling the call stack (maybe emptying it at each call), the ajax request should only trigger once after the timeout, I can't disable the slider navigation or use async: false because as I said users need to be able to spam click to go through the slider fast.
Any tips welcome, thanks in advance.
You need to cancel both your ajax call and timer functions before invoking again.
Assuming the customized function has the ajax call.
var xhr,timer;
function customizedFunction(){
xhr && xhr.abort();
xhr = $.ajax({
url: "/wp-admin/admin-ajax.php",
type:"POST",
data: {
action: "my_custom_color",
post_link: post_ID
}, success: function (response) {
$('.color').prepend(response);
},
})
}
colorsMonoSlider.events.on('indexChanged', () => {
timer && clearTimeout(timer);
timer = setTimeout(() => {
customizedFunction()
}, 1000);
});

Display loading icon once while waiting for AJAX call

I'm populating a table with data that automatically updates every 4 seconds using AJAX. I want to display a loading message while waiting for the AJAX to load on the initial page load only.
At the moment I have managed to display the loading message but the message appears every time the data is updated via AJAX (Every 4 seconds) - I want the loading message to only display on the initial page load before the AJAX loads initially. All subsequent AJAX updates should not display the loading message as the table has already been populated with data.
<div id="loading" style="display: none;">Loading..</div>
<script type="text/javascript">
$(document).ajaxStart(function(){
$("#loading").show();
}).ajaxStop(function() {
$("#loading").hide();
});
</script>
<script type="text/javascript">
var auto_refresh = setInterval(
function () {
$('#load_onlineusers').load('/online_players.php').fadeIn("slow");
}, 4000);
</script>
<div id="load_onlineusers"> </div>
Above is the code that is causing the loading message to display every 4 seconds.
Use beforeSend method to show loading message and control using a global variable:
var executed = false;
$.ajax({ url: "",
type: "",
data: "",
beforeSend: function() {
if (!executed) {
// Show loading
executed = true;
}
},
complete: function() {
// Hide loading
},
success: function(data) {
}
});

Execute ajax when html element visible on user screen

I have this script which makes ajax request when user reaches the end of the page. It is based on scroll event. At page load I am showing only 16 products on the user screen and when he scrolls down I wish to load another 16 products. My script is working but it executes more than one ajax request which is not what I want. The idea is just to show another set of 16 products. The script is:
$(window).scroll(function() {
if ($(window).scrollTop() + $(window).height() > $('.made').offset().top) {
//here I count how many products I have shown already
var productsshown = $(".productcell").length;
$('.made').hide();
$.ajax({
type: "post",
url: "./ajax/get_more_products.php",
data: {
"product": productsshown
},
dataType: 'json',
cache: false,
success: function(data) {
$("#bcontent").html(data);
$('.made').show();
}
});
}
});
As you can see I have a div which I am using as controler and when user see this div - the ajax is being executed. The result from ajax is being loaed into another div with id="content"
How to avoid scroll event to execute the ajax call more than once? I tried by hiding my controller div .made and upon ajax responce I am showing it again so it can be executed for another 16 products when user goes down to it again.. but ajax is always called executed more than once as I want it..
hmm, Here is a small addition to your code, adding a flag swiched whenever you load more items:
var _itemsLoading = false;
if ((!_itemsLoading) && ($(window).scrollTop() + $(window).height() > $('.made').offset().top)) {
//here I count how many products I have shown already
var productsshown = $(".productcell").length;
$('.made').hide();
_itemsLoading = true;
$.ajax({
type: "post",
url: "./ajax/get_more_products.php",
data: {
"product": productsshown
},
dataType: 'json',
cache: false,
success: function(data) {
$("#bcontent").html(data);
$('.made').show();
_itemsLoading = false;
}
});
}
Simple store the timestamp then you fire your ajax request and reset it then it returns or after 2 seconds.... then the timestamp is set don't fire your requests.
I don't handle the scroll event. I use setInterval() and I test if the position has changed since previous tic.
I just replaced
if ($(window).scrollTop() + $(window).height() > $('.made').offset().top) {
with:
if($(window).scrollTop() + $(window).height() == $(document).height()){
and used the page bottom as ajax controller.. It works now, thanks !

JQuery fadeOut not working for ajax post request

I have this JQuery code:
$(function(){
$('input#SearchGo').on('click', function(){
var searchid = $('input#search').val();
var dataString = 'search='+ searchid;
$.ajax({
type: "POST",
url: "tickets.php",
data: dataString,
cache: false,
success: function(html) {
$("#result").html(html).show();
}
});
return false;
});
});
that does a live search and posts data to a PHP page.
On every page i have a div with an id of overlay with a loading image while the page loads, then this code:
$(window).load(function(){
// PAGE IS FULLY LOADED
// FADE OUT YOUR OVERLAYING DIV
$('#overlay').fadeOut();
});
removes the overlay div once the page has loaded.
when i run the search query, the overlay div doesnt fadeOut at all, i tried adding $('#overlay').fadeOut(); within the success part of my function but it doesnt fadeOut the div.
UPDATE:
here is the HTML for the loading / overlay div
<div id="overlay" class="overlay">
<img src="images/integra_loading.gif" alt="Loading" width="12%" style="margin-top:15%;" />
<br /><br />
<h1>Loading...</h1>
</div>
$(function(){//this says the dom is ready
$('#overlay').fadeOut();
});
alternatively
$(document).on("ajaxComplete", function(){
$('#overlay').fadeOut();
});
Don't hide your ajaxloader with a function that is called from the html script wich is loaded through the ajax request. just show the loader before the request and hide it before replacing the html content with your response.
function loader(){
this.id = '#overlay'
};
loader.prototype.show = function(){
$(this.id).fadeIn();
};
loader.prototype.hide = function(){
$(this.id).fadeOut();
};
loaderObj = new loader();
$('.list').live('click', function() {
loaderObj.show();
$.ajax({
type: "GET",
url: "http://echo.jsontest.com/uid/12345/value/nuno_bettencourt",
cache: false,
dataType: "json",
success: function(json) {
// setTimeout only to delay the response and let the loader do his thing ;)
setTimeout(function(){
loaderObj.hide();
$('#ajaxResult').html("UID=" + json.uid + "\nName=" + json.value);
}, 2000);
}
});
i made you a small fiddle example http://jsfiddle.net/358Fz/1/
after doing your $.ajax, add a done. in that done, do the fadeout!
$.ajax({
...
}).done(function(){
$('#overlay').fadeOut();
});
you can add a .fail for when it fails, etc. see: http://api.jquery.com/jquery.ajax/
Just define the loader variable outside of your click event and then use it where needed. There will be less overhead if you only have to traverse the DOM once to locate the loader element. You can also change the on event to just a click event to save a few key strokes unless you need to delegate the event to another element. Also, you don't need to look up $(input#search) since ID's are unique. Removing the variable selector and just looking up the ID will be more efficient.
$(function() {
var $loader = $('#overlay');
$('.list').click(function(){
$loader.fadeIn();
$.ajax({
type: "GET",
url: "http://time.jsontest.com/",
dataType: 'json',
cache: false,
success: function(json) {
$loader.fadeOut();
$("#axajResponse").html('<b>Current Time:</b> ' + json.time).show();
}
});
return false;
});
});
In the above example I'm getting back the current time so that you can see the response change on each click event.
Here is an example: http://jsfiddle.net/bradlilley/jLG4g/

how to add delay function inside the ajax function

I am using ajax function to update and output the result.
how can I delay like 2 secs before the second update result get display again?
since right now, after the first update and second update, the text is the same like
'updated' I want to let user know this is the second time updated msg.
$.ajax({
type: "post",
url: "function.php",
data: "ajax=updateAward&" + inputs,
success: function(html) {
$('#message_award').html(''); //clear previous text
//delay 2 sec then display below?
$('#message_award').html(html) ;
}
});
Use setTimeout to execute a function after a delay (given in milliseconds). Here's a complete example:
$.ajax({
type: "post",
url: "function.php",
data: "ajax=updateAward&" + inputs,
success: function(html) {
setTimeout(function() {
$('#message_award').html(html);
}, 2000);
}
});

Categories