I have this function in jQuery that gets data from a page with POST, then sets the response into a div:
$("#go").click(function(){
$.post("get.php", {p: 'abc'}, function(data){
$('#result').html(data);
});
});
This works, but is there anyway to delay the data going into the #result tag by about 3 seconds?
Eventually I want the tag to say:
"Loading.", "Loading..", and "Loading..." for a second each, then show the data.
This is the syntax you should use.
var delayCounter = 3;
var delayTimer = '';
delayTimer = setInterval(function(){
if (delayCounter > 0){
$('#result').html('Loading...');
}else{
$('#result').html(data);
clearInterval(delayTimer);
}
delayCounter--;
},1000);
Whats happening here?
We use the delayCounter variable to count how many times we have delayed the action. Its starting value is 3 - so we will be "delayed" 3 times.
The delayTimer variable is the timer itself that will count each delay.
We use the setInterval function becuase that is exactly what we are wanting to do - set intervals between executing our code.
The clearInterval is pretty self explanatory - this ends and clears the timer.
For each iteration we decrease the delayCounter variable so that we can keep track of how many intervals have passed.
We use miliseconds to define the delay - here I have used 1000 which is 1 seconds (1000 milliseconds in one second).
One more addition you might like to implement is that instead of simply placing the "Loading" text in your element, to make it a little bit more dynamic by appending text to it.
What might be fun is to append the ellipsis to the word "Loading" to get an effect like :
First set the initial value to "Loading" then append each dot -
$('#result').html($('#result').html()+'.');
// Loading
// Loading.
// Loading..
// Loading...
That said you could also just take the animated gif and use that lazy-programmers :P
Try:
setTimeout(function() {
$('#result').html(data);
}, 3000);
To delay the execution of a function in JavaScript use the setTimeout method. Works a little like:
var doLater = setTimeout(function(){
alert('I like to wait 5 seconds');
},5000); //delay is stated in ms
In your case that would end up in:
$("#go").click(function(){
$.post("get.php", {p: 'abc'}, function(data){
var wait = setTimeout(function(){$('#result').html(data);},3000);
});
});
Edit: updated to add loading functionality.
$("#go").click(function(){
$.post("get.php", {p: 'abc'}, function(data){
window.intervalTimer = setInterval(function(data) {
if (!window.timeoutCount)
window.timeoutCount = 0;
if (++window.timeoutCount > 3) {
$('#result').html(data);
clearInterval(window.intervalTimer);
}
else
$('#result').html("Loading..")
}, 1000);
});
});
Try this:
$("#go").click(function(){
// Show loader here
$.post("get.php", {p: 'abc'}, function(data){
setTimeout(function () {
// Hide loader here
$('#result').html(data);
}, 3000);
});
});
$("#go").click(function(){
$.post("get.php", {p: 'abc'}, function(data) {
$('go').html('Loading.');
setTimeout("function() {
$('go').html('Loading..');
}",1000);
setTimeout("function() {
$('go').html('Loading...');
}",1000);
$('#result').html(data);
}
}
Related
I have this function already, which checks for change, and if true only updates this div.
jQuery(document).ready( function($) {
var auto_refresh = setInterval(function() {
$.ajax({
success: function(data) {
var result = $('<div />').append(data).find('div#vs').html();
$('div#vs').html(result);
}
})
}, 5000); // refreshing after every 5000 milliseconds
})
This works great, but now I want to add another function, I have made this javascript http://jsfiddle.net/jockebq/ocLh1rLd/
What it does is that if the height of the div #vs exceeds 300px it will add class .vscroll to #vs.
I have managed to make this work great in JSFiddle, but I cannot figure out how to merge this together with my javascript above.
I'm very much stuck, and I cannot find any information on how to do this. All help and tips are much appreciated!
I am sure i am missing something here but why not just
add it inside the function passed to setInterval and run it alongside the ajax call
var auto_refresh = setInterval(function() {
$.ajax({
success: function(data) {
var result = $('<div />').append(data).find('div#vs').html();
$('div#vs').html(result);
if (document.getElementById('vs').clientHeight > 300 )
$('div#vs').addClass('vscroll');
}
});
}, 5000); // refreshing after every 5000 milliseconds
})
PS: Your ajax better not be as you pasted it here!
EDIT: added the code in the success callback, since you probably want to resize when the new content is appended,as said by Pierre
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
I simply wonder if it's possible to make a function where you have a timer/clock which ticks and when there is no time left, a text/image will be removed. There will also be a message/text displaying notifying the user. (JQuery or Java)
I have tryed this using replace.child but without any promising result.
I have also looked around for any similar object but none found.
-Thanks.
here you go:
(function(){
var secondsLeft = 10,
$timerElm = $('#timer');
function updateTimer () {
$timerElm.text(secondsLeft--);
if (secondsLeft < 0) timesUp();
else setTimeout(updateTimer, 1000);
}
function timesUp () {
$('#target').remove();
$('<p>works like a charm!</p>').prependTo('body').hide().fadeIn()
}
updateTimer();
})()
and here is a live demo too!
http://jsbin.com/aguyuw/1/edit
enjoy!
You can use setTimeout function...
setTimeout(function() { $('#some_id').fadeOut('slow');}, 2000);
here 2000 is an optional value... you can change as you concern... and if you want to fadeout fast you can use 'fast' instead of 'slow'...
For javascript you can use something like this....
setTimeout(function(){you_function();},3000);
I'm having some problems updating a jquery progress bar. This progress bar isn't in the document during the page load, I'm adding it just when the user click on a button, ding something like this:
$(this).parent().append('<div class="progressbar"></div>');
$(this).parent().children('div.progressbar').show();
$(this).parent().children('div.progressbar').progressbar({value: 20});
then, using a timeout, I'm trying to update it
function updateProgressBar() {
$('.progressbar').each(function() {
myNewValue = getNewValue();
$(this).progressbar('value', 50);
});
setTimeout('updateProgressBar()', 5000);
}
setTimeout('updateProgressBar()', 5000);
the debug console complains saying: "Uncaught: cannot call methods on progressbar prior to initialiaztion: attempted to call method 'value'"
Googling here I found that the problem could be related to the inizialization of the progress bar after the loading of the page
Could someone help me?
Thanks in advance
-- edit --
thanks Bryan, I'm trying your solution but i doesn't work for me
Now I've this code
function startProgress() {
$(this).parent().append('<div class="progressbar"></div>');
$(this).siblings('.progressbar').show();
$(this).siblings('.progressbar').progressbar({value: 0});
function updateProgress() {
$('.progressbar').each(function() {
myNewValue = getNewValue($(this).parent().parent().attr('id'));
$(this).progressbar('value', myNewValue);
});
setTimeout('updateProgress', 5000);
}
setTimeout('updateProgress', 5000);
}
The console is sayng there's no updateProgress defined
-- edit --
many many thanks!!!
Now i've a quite definitive version that works...
Here my current code
if($(this).siblings('.progressbar').size() == 0) {
$(this).parent().append('<div class="progressbar"/>');
$(this).siblings('.progressbar').progressbar({value: 0});
}
$(this).siblings('.progressbar').show();
function updateProgress() {
$('.progressbar').each(function() {
myParams = 'service=' + $(this).parent().parent().attr('id') + '&content=' + $(this).parent().attr('id')
myUrl = '/datacast/content_progress/?' + myParams;
theValue = $(this).progressbar('value');
$.get(myUrl, {}, function(aReply) {
myData = aReply.split(' ');
myItemId = myData[0];
myValue = parseInt(myData[1]);
try {
$(".item[id = " + myItemId + "]").children(".progressbar").progressbar('value', myValue);
}
catch(myError) {
//alert(myError);
}
})
});
setTimeout(updateProgress, 5000);
}
setTimeout(updateProgress, 5000);
As you can see I've add a control if there is already a progress bar as i pass thorough that code several times.
The progress bar is updated every time, but the console complains saying "TypeError: Cannot call method 'apply' of undefined", so I had to add the try block with an empty catch body to drop the error. The page works but it could be interesting if you have an idea why there's that error
Had the same problem
Apparently you must use the format progressbar({value:30}) the first time
If you use progressbar(value,30) the first time then you get this exception.
Ok, I can't believe I missed that. The problem is that you're passing a string to the setTimeout function. This will cause it to lookup the name of the function in global scope, which it's not.
Change both of these calls:
setTimeout('updateProgress', 5000);
to
setTimeout(updateProgress, 5000);
Make sure that you're using the exact same selector in your update method as in the initialization method.
In the provided code, you're doing something like $(this).parent().children().find('.progressbar') and then in the update you're just doing $('.progressbar'). That second call could potentially return items that the first one didn't, and those items wouldn't have a progress bar initialized.
This code worked fine for me:
$(function(){
$('body').append('<div class="progress"></div>');
var val = 10;
$('.progress').progressbar({value:val});
function updateProgress() {
val += 10;
$('.progress').progressbar('value', val);
if(val < 100)
setTimeout(updateProgress, 1000);
}
setTimeout(updateProgress, 1000);
});
Also, remember that you don't actually need that call to each() as jquery methods should automatically apply to all elements matched with that selector.
Example:
$('.red').each(function(){ $(this).css({color:'red'}); });
is redundant, and the same can be achieved with:
$('.red').css({color:'red'});
Oh, and here's a freebie:
$(this).parent().children().find('.progressbar')
can be shortened to: $(this).siblings('.progressbar')
Hello I am trying to simulate the fade method provided in mootools 1.2 in 1.1.
Due to development restrictions I have to use 1.1. I basically update my div after an ajax response and I want this div to get cleared after some time
var resp = Json.evaluate( response );
$(elem).setHTML('Thanks!'); //Show the message for a while and then clear the div
Thanks for your responses I'm trying to use Dimitar's approach but since I'm not a MooTools expert at all I will need some help
window.addEvent('domready', function(){
$(link_id).addEvent('click', function(){
var a = new Ajax( '{$url}'+this.id, {
method: 'get',
onComplete: function(response) {
var resp = Json.evaluate( response );
$(resp.id).setHTML('Thank you');
//My stupid approach //setTimeout('$("'+divname+'").setHTML("")',3000);
}
}).request();
});
}
So in the context of my code where should I define the Element.extend you propose?
I just tried to add it inside the domready function but couldn't recognise the fade method
to define element prototypes in 1.1x you need Element.extend
Element.extend({
fade: function(from, to, remove) {
new Fx.Style(el, "opacity", {
duration: 500,
onComplete: function() {
if (remove)
this.element.remove();
}
}).start(from, to);
}
});
var el = $("elem");
el.setHTML('Thanks!');
(function() {
el.fade(1,0, true);
}).delay(2000);
in this example I have created a simple element.fade() which DOES need start and end value and can optionally remove the element from the dom etc if you dont plan on needing it again.
here's a working example: http://jsfiddle.net/dimitar/cgtAN/
edit as per your request to empty the html:
window.addEvent('domready', function() {
$(link_id).addEvent('click', function() {
new Ajax('{$url}' + this.id, {
method: 'get',
onComplete: function(response) {
var resp = Json.evaluate(response), target = $(resp.id);
target.setHTML('Thank you');
(function() {
target.empty();
}).delay(3000);
}
}).request();
});
});
Never used Mootools much, but after a bit of jsfiddle, it seems like something along these lines would work:
function fadeAfter(id, msec)
{
setTimeout(function(){
new Fx.Styles(id).start({'opacity': ['1', '0']});
}, msec);
}
Ok I found a solution using setTimeout
setTimeout('$("'+divname+'").setHTML("")',3000);
where 3000 the waiting time in milliseconds