So i have looked around and most of the code for this looks needlessly beefy. I am looking for lightweight ajax code that refreshes a div with an action like:
load('boo.php')
And I need it to load first on the page opening (ie no delay) then every x seconds refresh (without fade) so you cannot notice a change unless my Database rows have updated but I can do the db bit.
I think i would need something like:
onreadystatechange
to load when the page loads? Eh im not too sure on this :( any help would be much appreciated!
Thanks!
I totally recommend using some library for cross-browser support and tested code, e.g. jQuery.
With jQuery, it's as simple as
$.get('boo.php', function(data){$('#divId').html(data);});
You can wrap this in a function and call it on document ready, then use setInterval as suggested by #M1K1O
Update
To run the code when the DOM is loaded, the jQuery API documentation for ready states that
All three of the following syntaxes are equivalent:
$(document).ready(handler)
$().ready(handler) (this is not
recommended)
$(handler)
Here is a complete example:
function refreshDiv()
{
$.get('boo.php', function(data){$('#divId').html(data);});
}
$(function()
{
refreshDiv();
setInterval(refreshDiv, x * 1000); // x is the number of seconds
});
var counter = 0;
var timer = null;
function progressBar(){
if (timer) {
clearTimeout(timer);
timer = null;
return;
}
timer = window.setInterval(function(){
load('boo.php');
}, 10);
}
window.onload = function() {
progressBar();
};
Try this
Do you use some libries like Jquery ?
Here is some code on jquery for.
function update()
{
$.get(<URI>,{check:1},function(data){
$('#div').html(data);
});
setTimeout('update()',1500);
}
$(function(){
update();
});
Related
Ok , I'm having trouble to solve this , I'm a php / C# web developer , and have no experience or knowledge in Javascript, I have to do just this one thing that needs Javascript:
When a certain page loads, a counter starts. The client must stay on this page for 20 seconds. after, I want to execute php code.
So there are 2 issues concerning me, first: how do I stop the counter, if client leaves the page (meaning the page is not in focus).
2) How can I execute php in javascript? , or call a php function from Javascript.
The code I have so far is this:
<html>
<head>
</head>
<body>
<div id='timer'>
<script type="text/javascript">
COUNTER_START = 20
function tick () {
if (document.getElementById ('counter').firstChild.data > 0) {
document.getElementById ('counter').firstChild.data = document.getElementById ('counter').firstChild.data - 1
setTimeout ('tick()', 1000)
} else {
document.getElementById ('counter').firstChild.data = 'done'
}
}
if (document.getElementById) onload = function () {
var t = document.createTextNode (COUNTER_START)
var p = document.createElement ('P')
p.appendChild (t)
p.setAttribute ('id', 'counter')
var body = document.getElementsByTagName ('BODY')[0]
var firstChild = body.getElementsByTagName ('*')[0]
body.insertBefore (p, firstChild)
tick()
}
</script>
</div>
</body>
</html>
and I also want the timer to start ticking when the client gets back on page
Thank you very much for ur help in advance
You could do this using jQuery.
Recycling an old Stackoverflow post, try this:
var window_focus;
var counter = 1000;
// on focus, set window_focus = true.
$(window).focus(function() {
window_focus = true;
});
// when the window loses focus, set window_focus to false
$(window).focusout(function() {
window_focus = false;
});
// this is set to the ('click' function, but you could start the interval/timer in a jQuery.ready function: http://api.jquery.com/ready/
$(document).one('click',function() {
// Run this function every second. Decrement counter if window_focus is true.
setInterval(function() {
$('body').append('Count: ' + counter + '<br>');
if(window_focus) { counter = counter-1; }
}, 1000);
});
Demo and old post
DEMO | Old So post
Update
Probably because the demo runs in 4 iframes, the $(window).focus bit only works on the iframe actually running the code (the bottom-right window).
jQuery
jQuery.com (How jQuery works) | Example (back to basics halfway down the page) | If you use the 2nd link, also read this
In regards to your first question about detecting if the window is out of focus, see this answer: Is there a way to detect if a browser window is not currently active?
It is possible, but only very new browsers support this so it may not be useful based on current browser support.
To trigger PHP code from Javascript, you would have to make an AJAX call to a server-side PHP script to invoke PHP since JS is client-side and PHP is server-side.
I have a PHP notification system, and the amount of notifications is put into a DIV using jQuery. The only problem is that when there are 0 notifications, the empty DIV still shows up. This is the jQuery I am currently using:
$(document).ready(function() {
$.get('/codes/php/nf.php', function(a) {
$('#nfbadge').html(a);
$('#nfbadge:empty').remove();
})
});
setInterval(function() {
$.get('http://localhost/codes/php/nf.php', function(a) {
$('#nfbadge').html(a);
$('#nfbadge:empty').remove();
})
}, 8000);
The only problem is that if at document load there is 0 notifications and a notification is added, the badge will not show up, so basically if the element is removed it won't come back unless the page is reloaded, but I made the notification system so that the page wouldn't have to be reloaded. How can I fix this?
.remove() takes the element out of the DOM as well as the content. This is why it doesn't come back unless you reload. Use .fadeOut() or .hide() instead
You should probably do something more like this:
var elm = $('#nfbadge'),
T = setInterval(getCodes, 8000);
function getCodes() {
$.get('/codes/php/nf.php', function(a) {
elm.html(a);
if (elm.is(':empty') && elm.is(':visible')) {
elm.hide();
}else{
elm.show();
}
});
}
Will need some more work on your part, but should get you on the right track!
If you have control over the PHP, you shouldn't be using jQuery to be removing DIVs, it's a waste of resources and load time, even if it's just a few lines of code.
In your PHP template you should include the #nfbadge div in a conditional statement, something like:
if($notifications) {
echo '<div id="nfbadge">';
//notification stuff
echo '</div>';
}
Then with your jQuery code you could do something like the following:
var $nfbadge = $('#nfbadge');
if($nfbadge) {$nfbadge.html(a)}
Why don't you just make the div hidden?
http://www.randomsnippets.com/2008/02/12/how-to-hide-and-show-your-div/
I'm working with jqueries address change event and am hitting a roadblock when a user copies and pastes a URL in the browser. I need to fist load a portion of the page that contains a form. I could do this after every pagination call but it seems really ineffecient.
Here is my current code block:
$.address.change(function(e) {
var urlAux = e.value.split('=');
var page = urlAux[0];
var start = urlAux[1];
if (page == "/visits") {
$.address.title("Profile Views");
if (start) {
$('#start').val(start);
// ***** If a user has copied and pasted this URL with a start value then I first need to load visits.php in the main div tag. Is it possible to see if this is loaded or not?
$.post("visits_results.php", $("#profile_form_id").serialize(),
function(data) {
$('#search_results').html(data);
location.href = "#visits=" + start;
});
}
else {
var args = localStorage.getItem("visits");
$('#main').load("visits.php?" + args, function () { });
}
}
My attempted work around was this:
var args = localStorage.getItem("visits");
$('#main').load("visits.php?" + args, function () {
$('#start').val(start);
$.post("visits_results.php", $("#profile_form_id").serialize(),
function(data) {
$('#search_results').html(data);
location.href = "#visits=" + start;
});
});
There must be a better way...this is realoading the same portion of the page (visits.php) with every pagination event. Is there a better way to load URLs and not have them trigger an address change?
Using paul's work around from his comments, but instead of Regex'ing html content in the visits.php form this solution will look for data() attached to #mainID.
Paul's work around notes:
After a bit more hacking I came up with this solution that seems to do
the trick. I'm not sure how good it is but it seems to do the trick. I
now get the main div id and do a regex match on a unique string in the
form. If I don't see it I load the form and then load the results. Not
sure if this is good practice or not but it seems to solve my issue.
Methodology to use .data() instead of a regex search of visits.php's html:
/*check if we're missing visits.php by looking for data() flag*/
if( !($("#main").data()["hasVisitsPhp"]) ){
var args = localStorage.getItem("visits");
$('#main').load("visits.php?" + args, function () {
$('#start').val(start);
$.post("visits_results.php", $("#profile_form_id").serialize(),
function(data) {
/* we've loaded visits.php, set the data flag on #main*/
$('#main').data("hasVisitsPhp","loaded");
$('#search_results').html(data);
location.href = "#visits=" + start;
});
});
}
try window.location.hash instead. Changing the whole href can/will trigger a whole-page reload, while changing just the hash by itself should at most cause the page to scroll.
The thing is, I can do both, but I can't make them work immediately one after another, it does the first in the 1st clock, and the second in the 2nd clock. I've also tried with 1 div inside another but it's the same. Here's the code:
the script:
$(document).ready(function() {
$("#chatRoomSub").load("chatUpdate.php");
refreshId = setInterval(function() {
$("#chatRoomSub").load('chatUpdate.php');
var object = document.getElementById('chatRoom');
object.scrollTop = object.scrollHeight;
}, 5000);
$.ajaxSetup({ cache: false });
});
the body:
<div class='chatRoom' id="chatRoom">
<div class='chatRoomSub' id="chatRoomSub">
ainda nada foi escrito...
</div>
</div>
You need to use a callback function on the .load() which does the scrolling.
$("#chatRoomSub").load("chatUpdate.php", function() {
// scroll down
});
This way, the scrolling will occur immediately after the content is loaded.
You need to use call back function of jquery. Call back function is something that executes after event if i take an example .load("You code",function())..after loading your code, it will execute "code", it will execute function...
Im using the following to open/close a div
$(".alerts").click(function(){
$(this).toggleClass("active").next().slideToggle(50);
But I want a certain function to trigger only if the box was closed and is being opened, how can I determine this? I prefer not to use cookies or anything like that
thanks!
You can use the visible selector with the is method like this -
$(document).ready(function()
{
$(".alerts").click(function()
{
if($(this).toggleClass("active").next().is(":visible"))
alert("It's visible");
$(this).toggleClass("active").next().slideToggle(50);
});
});
An example on jsfiddle.
The -
if($(this).toggleClass("active").next().is(":visible"))
alert("It's visible");
portion is checking to see if the next element of this is visible or not. If it is, then it returns true. As a result, the alert method gets executed.
Here is the documentation for the visible selector and here is the documentation for the is() method.
You can add a class to the div and check for it with hasClass():
$('.alerts').live('click', function() {
if($(this).hasClass('active')) //close
$(this).removeClass('active').next().slideUp(50);
else //open
$(this).addClass('active').next().slideDown(50);
});
When checking for DOM elements/attributes that have been changed by Javascript, use live() rather than e.g. click().
If your .alerts element has a different CSS style when it has the .active class, you should run the addClass() and removeClass() functions after the slide events have completed, like so:
//same thing, but wait for animation to complete
$('.alerts').live('click', function() {
var thisbtn = $(this);
if(thisbtn.hasClass('active')) { //close
thisbtn.next().slideUp(50, function() {
thisbtn.removeClass('active');
});
} else { //open
thisbtn.next().slideDown(50, function() {
thisbtn.addClass('active');
});
}
});