Timer for Simple Ajax loaded page - javascript

Have a simple ajax for loading content into a page.
What I want is for the loaded content to wait a set amount of time before showing on the page. (before the fadeIn)
I tried using jQuery's .delay() function after it fades the #body in but it did not work.
Can anyone point me in the right direction?
Thank you in advance for your time
JS
var default_content="";
$(document).ready(function(){
checkURL();
$('ul li a').click(function (e){
checkURL(this.hash);
});
//filling in the default content
default_content = $('#pageContent').html();
setInterval("checkURL()",250);
});
var lasturl="";
function checkURL(hash)
{
if(!hash) hash=window.location.hash;
if(hash != lasturl)
{
lasturl=hash;
// FIX - if we've used the history buttons to return to the homepage,
// fill the pageContent with the default_content
if(hash=="")
$('#pageContent').html(default_content);
else
loadPage(hash);
}
}
function loadPage(url)
{
url=url.replace('#page','');
$('#body').hide ();
$('#loading').css('visibility','visible');
$.ajax({
type: "POST",
url: "load_page.php",
data: 'page='+url,
dataType: "html",
success: function(msg){
if(parseInt(msg)!=0)
{
$('#pageContent').html(msg);
$('#body').fadeIn( 'slow' );
$('#loading').css('visibility','hidden');
}
}
});
}
PHP
if(!$_POST['page']) die("0");
$page = (int)$_POST['page'];
if(file_exists('pages/page_'.$page.'.html'))
echo file_get_contents('pages/page_'.$page.'.html');
else echo 'There is no such page!';
?>

You want the setTimeout Javascript function.
setTimeout(function(){
$('#pageContent').html(msg);
$('#body').fadeIn( 'slow' );
$('#loading').css('visibility','hidden');
}, 5000);
This will wait 5s für the content to be set.

You can use setTimeout:
setTimeout(checkURL(/* value to pass */),250);
Please don't quote calls to functions, as what's in a " " will be handled as a string, not a function call.

Related

div should be refreshed every three seconds using jquery and ajax

below is my script in that, particular div should be refresh every three seconds. how to add the time interval in my code using jquery and ajax?
<script>
$(document).ready(function () {
$('#data_form').on('submit', function (e) {
var form_data = $(this).serialize();
$.ajax({
type: "POST",
url: '<?php echo base_url(); ?>index.php/Profile_cntrl/supplier_communication',
data: form_data,
success: function (data)
{
scrollDown();
var message = $("#messagee").val();
$('#chat_log').append('<div class="row msg_container base_sent active"><div class="row msg_container base_receive"><div class="col-md-12 col-xs-12"><div class="messages msg_receive"><p><a>' + message + '</a></p></div></div></div></div>');
$('#messagee').val('');
},
error: function ()
{
alert('failed');
}
});
e.preventDefault();
});
scrollDown();
function scrollDown() {
$('.msg_container_base').animate({scrollTop: $('.msg_container_base').prop("scrollHeight")}, 200);
}
});
</script>
To refresh the div every 3Sec.
You can use "setInterval" function.
And to stop this interval you can use "clearInterval" function.
The simple code is as follows:
var refreshIntervalId = setInterval(function(){
// alert("Hello");
//Your Div's ID
}, 3000);
/* later */
clearInterval(refreshIntervalId);
This code simply calls the alert every 3seconds,so modify the above code and put the div's id to be refreshed.
You can use setInterval javascript function for that. check the code snippet below
setInterval(scrollDown, 3000);
I hope this will help you. Please check below code.
function animatedText() {
$('.text').animate({ opacity: 1 }, 200, function() {
$('.text').animate({ opacity: 0 }, 200);
});
setTimeout(function() {
animatedText();
},3000);
}
animatedText();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text">Animated Text</div>
Use
setInterval(function(){
getMessage();
}, 3000);
setIterval lets you to repeat a function or a code block every n seconds.
I think you should add your ajax call into a function.
function getMessage () {
//Your ajax call here
}
This way the code could be reused more times without repeating it.

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

Reload function after Ajax call

I have a plugin raty (http://wbotelhos.com/raty) that is loaded to document.ready, the page content changes at the click of a button reloading a part of the DOM, and the document is not ready "recalculated" and I will not reload all javascript (there are other similar behavior) I tried this solution but without success
function star(){
alert("star");
...code plugin...
}
$(document).ready(function() {
star();
});
$.ajax({
..code..
done: function(creaStella) {
alert("D");
star();
},
complete:function(){
alert("C");
star();
},
});
After call ajax i have alert("star") but i haven't my div populated
Incorrect usage of $.ajax
$.ajax({
..code..
success: function(creaStella) {
//code to populate div goes here
alert("complete");
star();
}
}).done(function(){
//or here
alert("complete2");
});
use success/done as show (or both).
I resolve in this Way..(promise().done)
also form with jquery validate plugin before dosen't works
function star(){
//plugin star
}
$(document).ready(function() {
formJqueryValidate1();
formJqueryValidate2();
star();
});
function formJqueryValidate1() {
//my check
function formJqueryValidate2() {
//my check
}
$.ajax({
success: function(msg) {
$('#myid').html(msg.template).promise().done(function(){
formJqueryValidate1();
formJqueryValidate2();
star();
});
}
}
});

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.

Categories

Resources