I am using this code to refresh a PHP page:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">// <![CDATA[
$(document).ready(function() {
$.ajaxSetup({ cache: false }); // This part addresses an IE bug. without it, IE will only load the first number and will never refresh
setInterval(function() {
$('.container').load('integra_data.php');
}, 2000); // the "3000" here refers to the time to refresh the div. it is in milliseconds.
});
// ]]></script>
<div class="container"><h3>Loading Data...</h3></div>
in javascript, rather than refreshing every X Seconds, can i make it refresh once the previous refresh has finished?
Use setTimeout instead setInterval.
$(document).ready(function() {
$.ajaxSetup({ cache: false });
setTimeout(function() {
$('.container').load('integra_data.php');
}, 2000);
});
$( document ).ready(function(){}) everything inside of this will be ran after load of page has finished. so there should be delay of 2 seconds here..
If I got you right you want to refresh the content of the div in an infinite loop, right? If this is right, you could pass your call to load() as complete callback. You could do somethin like this (recursion):
$(document).ready(function() {
var loadFunction = function () {
$('.container').load('integra_data.php', loadFunction);
}
$.ajaxSetup({ cache: false });
loadFunction();
});
The loadFunction() will call itself every time the last run has finished. Refer to the docs if you want to know more about the complete callback. If you add a little delay, since it's not always the best idea to make request as fast as possible use the setTimeout() function. You could add it to the complete callback.
Related
I am using a plugin called mixitup that makes sure I have a masonry layout with some animations.
The masonry comes from another page which gets loaded in through ajax. I have a search bar which searches for photos and returns them from the masonry page. The issue is this works the first time but not the second time and so on. Why is that?
My code for the search input:
$('.photosearchinput').keyup(function(e) {
clearTimeout($.data(this, 'timer'));
if (e.keyCode == 13){
searchphotos(true);
}else{
$(this).data('timer', setTimeout(searchphotos, 500));
}
});
My function that makes the ajax call and which has my masonry mixitup function in the complete:
function searchphotos(force) {
var photoform = $(".photosearchform").serialize();
$.ajax({
type:'post',
url:"includes/photoresults.php",
data:({photoform: photoform}),
success:function(data){
$( "#searchphotos" ).show().empty().append( data );
},
complete:function(){
// I tried calling #masongallery from the body (body always stays the same and does not get added again)
$('body').find('#masonrygallery').mixItUp({
selectors: {
target: '.tile',
filter: '.filter',
sort: '.sort-btn'
},
animation: {
animateResizeContainer: false,
effects: 'fade scale'
}
});
}
});
}
I thought maybe the DOM gets reloaded and jquery cannot find the element #masonrygallery anymore so I tried calling it like this: $('body').find('#masonrygallery').mixItUp({ the body never gets reloaded so maybe this would fix it, but no. I get the same result. It works the first time, but not any time after that.
I have made a video to show what I mean: https://streamable.com/njy6x7
I get no errors in my console. And when I look in the network tab to see what ajax is retrieving, I see the correct images, they are just not visible as masonry layout (in fact they are not visible on the page at all but this is because of the plugin).
Before posting this I've browsed some existing topics but couldn't get anything helpful, I tried some things to fix this but it failed.
I'm developing a website, and today I wanted to code a basic dark mode switch in Javascript :
<script type="text/javascript">
function switchWhite() {
document.getElementById("body").className = "";
document.getElementById("menubar").className = "navbar navbar-expand-lg navbar-light bg-light";
}
function switchDark() {
document.getElementById("body").className = "dark";
document.getElementById("menubar").className = "navbar navbar-expand-lg navbar-dark bg-dark";
}
function triggerSwitch() {
if ( document.getElementById("body").className.match("dark") ) {
switchWhite();
} else {
switchDark();
}
}
</script>
<button onclick="triggerSwitch()">Switch Mode</button>
This works just fine but there is an auto-refresh on the website, which is triggered every 30 seconds and which refreshes only specific blocs (like menubar) :
<script>
setInterval(function()
{
$(document).ready(function() {
$("#menubar_refresh").load(document.URL + " #menubar");
});
}, 30000);
</script>
Which also works fine, but I cannot mix these two features because once I switch to dark mode theme, after 30 seconds (when the auto-refresh is triggered), it gets back to light mode (the original state of the page).
Though is this normal, so I tried to put the dark mode back right after the bloc refreshes, like this :
<script>
setInterval(function()
{
$(document).ready(function() {
$("#menubar_refresh").load(document.URL + " #menubar");
});
switchDark(); // here
}, 30000);
</script>
It simply doesn't work, the bloc (and only this bloc, not the whole page) still gets back to the original state (light).
I've noticed that it switches to dark mode for a few milliseconds, and gets back to the original state.
I thought that the switchDark(); call is executed at first, even before the whole function finishes, in a way that the dark mode is set and then the bloc is refreshed.
So I tried setting a variable to block the execution of switchDark(); call before everything else finished executing, but the result is the same, which makes me think that my hypothesis is wrong.
Could you please help me to figure out what the problem is here ?
I can add more code snippets if you need them.
Thanks a lot
load() is asynchronous so you need to modify any new content in the complete callback.
Something like:
$("#menubar_refresh").load(document.URL + " #menubar", switchDark);
Or more verbose version:
$("#menubar_refresh").load(document.URL + " #menubar", function(){
// new content now exists
// add logic as to which theme method to call
if(isDark){
switchDark();
}
});
So, I'm in agreement with the answer by #charlietfl. But there is a flaw in your code due to misunderstanding and misinterpretation of javascript's event handler asynchronous nature.
The code in question is this:
<script>
setInterval(function() {
$(document).ready(function() {
$("#menubar_refresh").load(document.URL + " #menubar"); });
switchDark(); // here
},
30000);
</script>
You are using $(document).ready inadvertently as an if statement not as an event handler. Apparently, your code says after 30secs, if the document is ready, refresh the document and switch to a dark theme. But actually, your code means after 30secs, attach the ready state change handler to document. In this handler, asynchronously refresh the page and [immediately] switch to a dark theme.
Now, here lies your problem:
Though there is practically one, there is no 'absolute' guarantee that the document will be ready after 30secs. Consequently, your code setup isn't one that actually executes after 30secs.
There is no practical and absolute guarantee that the page will refresh completely before switchDark() executes. Why? The code for refreshing is asynchronous. Consequently, your switchDark() function almost never executes as you expect it to (though it always executes) since you expect it to use code from the newly loaded page.
A better and more meaningful code setup is to include setInterval inside $(document).ready handler and use a callback with the load() method for any code you want executed after the load() method.
<script>
$(document).ready(function() {
setInterval(function() {
$("#menubar_refresh").load(document.URL + " #menubar", function() {
switchDark(); // here
});
}, 30000);
});
</script>
I'm using jQUERY+AJAX to refresh a couple of divs every X seconds. I'd like to know what would be the way to load these divs immediately (for the first time) after the page was loaded and then wait (for eg. 30 seconds) for every refresh.
I've seen around that you name a function and then call the refresh. The truth is that I can't figure it out how to work it out with my code.
Here are my lines of code:
// <![CDATA[
$(document).ready(function() {
$.ajaxSetup({ cache: false }); // This part addresses an IE bug. without it, IE will only load the first number and will never refresh
setInterval(function() {
//DIVs that are being loaded
$('#item01_tobeloaded').load('items/item01.php');
$('#item02_tobeloaded').load('items/item02.php');
}, 30000); // the "30000" here refers to the time to refresh the div. it is in milliseconds.
});
// ]]>
Any help will be really appreciated :)
Thanks!
<script type="text/javascript">
$(document).ready(function() {
$("#refresh").load("refresh.php");
var refreshId = setInterval(function() {
$("#refresh").load('refresh.php?' + 1*new Date());
}, 1000);
});
</script>
This little script loads and refreshes the div 'refresh' continuously, you can adjust it to your needs by changing 1000 to whatever value you need. 1000 will refresh it every second.
This line
$(document).ready(function() {
$("#refresh").load("refresh.php");
loads yor content on document ready, afterwards you can stick with your code
I have this JQuery code that loads a php file into a div every X Seconds
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">// <![CDATA[
$(document).ready(function() {
$.ajaxSetup({ cache: false }); // This part addresses an IE bug. without it, IE will only load the first number and will never refresh
setInterval(function() {
$('.container').load('dashboard.php');
}, 10000); // the "3000" here refers to the time to refresh the div. it is in milliseconds.
});
// ]]></script>
<div class="container"><h3>Loading Dashboard...</h3></div>
when the loading starts it shows the Loading Dashboard text but then every X seconds it just refreshes the content in the background. how can i show some sort of loading image each time it refreshes?
How about this:
1) at the very top of your setInterval function, before you execute the load, set the background of that container class to be a loading image (or however you want to display it).
2) use the callback function of .load (https://api.jquery.com/load/) to remove that loading image when the load has completed.
Here's a fiddle illustrating the direction you should take...
http://jsfiddle.net/j5sZc/
HTML
<div class="wrapper">
<h3 class="loader">Loading Dashboard...</h3>
<div class="container"></div>
</div>
JS
$(document).ready(function() {
$.ajaxSetup({ cache: false }); // This part addresses an IE bug. without it, IE will only load the first number and will never refresh
var $loader = $(".loader"), // cache references to loader and container
$container = $(".container");
setInterval(function() {
$loader.show(); // show loader when request is initialized
$container.empty().load('dashboard.php', function(){
$loader.hide(); // hide loader once new content is loaded
});
}, 10000); // the "3000" here refers to the time to refresh the div. it is in milliseconds.
});
I have a Div Tag that has a php include to fill that div with information
what I want to do is make it so that the page is called every 15s so it can update the information there without having to reload the whole webpage.
I've tried to do this with JavaScript/jQuery and I just can't seem to get it to work
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('.View').load('Small.php').fadeIn("slow");
}, 15000); // refresh every 15000 milliseconds
</script>
<div class="View"><?php include 'Small.php'; ?></div>
this is what I have after searching some, and what happens is, it loads the Small.php but it doesn't refresh it or update the info every 15 seconds.
please help!
I should add all my php arrays that should show up are all executed in the Small.php and the page I'm including it into is just so it's isolated.
EDIT: What No One noticed was that my first script referencing jQuery did not have a closing tag, and that was breaking my second script. after adding in a proper closing tag, the script was finally working, but the fadeIn does not show properly without first using a fadeOut.
Your code works, but the fadeIn doesn't, because it's already visible. I think the effect you want to achieve is: fadeOut → load → fadeIn:
var auto_refresh = setInterval(function () {
$('.View').fadeOut('slow', function() {
$(this).load('/echo/json/', function() {
$(this).fadeIn('slow');
});
});
}, 15000); // refresh every 15000 milliseconds
Try it here: http://jsfiddle.net/kelunik/3qfNn/1/
Additional notice: As Khanh TO mentioned, you may need to get rid of the browser's internal cache. You can do so using $.ajax and $.ajaxSetup ({ cache: false }); or the random-hack, he mentioned.
try this
<script type="text/javascript">
window.onload = function(){
var auto_refresh = setInterval(
function ()
{
$('.View').html('');
$('.View').load('Small.php').fadeIn("slow");
}, 15000); // refresh every 15000 milliseconds
}
</script>
Your html is not updated every 15 seconds. The cause could be browser caching. Add Math.random() to avoid browser caching, and it's better to wait until the DOM is fully loaded as pointed out by #shadow. But I think the main cause is the caching
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js" />
<script type="text/javascript">
$(document).ready(function(){
var auto_refresh = setInterval(
function ()
{
$('.View').load('Small.php?' + Math.random()).fadeIn("slow");
}, 15000); // refresh every 15000 milliseconds
});
</script>
The code you're using is also going to include a fadeout effect. Is this what you want to achieve? If not, it might make more sense to just add the following INSIDE "Small.php".
<meta http-equiv="refresh" content="15" >
This adds a refresh every 15seconds to the small.php page which should mean if called by PHP into another page, only that "frame" will reload.
Let us know if it worked/solved your problem!?
-Brad
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js" />
<div class="View"><?php include 'Small.php'; ?></div>
<script type="text/javascript">
$(document).ready(function() {
$('.View').load('Small.php');
var auto_refresh = setInterval(
function ()
{
$('.View').load('Small.php').fadeIn("slow");
}, 15000); // refresh every 15000 milliseconds
$.ajaxSetup({ cache: true });
});
</script>