Hope someone can help. I am new to javascript so please forgive any mistakes. I am trying to achieve the following:
I have an index page with an html table, split up into four quarters. Each quarter has a DIV ID, and an ajax load via jquery will reload individual DIV's with a PHP page sucessfully, after a certain delay.
What I am trying to do, is for one of the quarters, rotate three PHP pages in the DIV every 15 minutes, and keep looping. I had setup an array with three php sites in, and sucessfully used this with a counter variable to call the relavent entries in the array via jquery. If I put in the count number in the ajax code it works. I am now struggling to see how I can increment the counter, and also reset it once it has reached the third page.
I do not know if I can use the ajax.complete function to assist, as I dont know if I can put "standard" javascript inside this function.
Thanks for any assistance - my code is below:
var count = 0;
var page = new Array("page1.php","page2.php","page3.php");
var delay = ("9000");
(
function($)
{
$(document).ready(function()
{
$.ajaxSetup(
{
cache: false
});
var $container = $("#DivID");
$container.load(page[count]);
var refreshId = setInterval(function()
{
$container.load(page[count]);
}, delay);
});
})
(jQuery);
try this
var refreshId = setInterval(function()
{
$container.load(page[count]);
count = (count+1) % 3
}, delay);
This way when count reaches 3 it will be reset to 0. Percent sign is the module division
Do not use Set Interval.
it will lag and chain if the page load is slow, crashing your site
use setTimeout:
setTimeout(function_name, delay);
var function_name = function() {
$container.load(page[count], function(){
count = (count+1) % 3;
setTimeout(function_name, delay);
});
}
this way, the timeout isn't chained, it fires once the page load is completed
Related
I am building a chat. I have this Jquery working code which calls logs.php every second and refreshes the chat.
$(document).ready(
function(e) {
$.ajaxSetup({cache:false});
setInterval(function() {
$('#chatlogs').load('logs.php');
updateScroll();
}, 1000);
}
);
As you can see, also updateScroll, a JS function on my page, gets called. Updatescroll creates a variable, which I would like to pass on to logs.php, is there any way to do this? In other words, updatescroll basically checks everysecond if the user has scrolled up to the top of the chat. If so, I am gonna tell logs.php to load -say - another 10 messages. But in order to do this, I have to have something that from updatescroll passes on to the Jquery function and thus onto logs.php. You get it? Thanks
First, when it comes to ajax, I would recommend using a window.setTimeout, intervals can get tricky when you are running things asynchronously (if one call hangs you can end up with multiple calls to the same script).
so something more like:
(function($){
var update_messages = function(){
var count = updateScroll();
$('#chatlogs').load('logs.php?count='+count, function(){
window.setTimeout(update_messages, 1000);
});
}
$(document).ready(function(){
$.ajaxSetup({cache:false});
update_messages();
});
})(jQuery);
Then in your PHP script the "count" would be available via $_GET['count'].
EDIT: you can see an anonymous function is being sent as a second argument to load, this will be called AFTER the AJAX call is complete, so we can make sure only 1 of these is running at a time
I am stuck again with a problem, let me explain it to you.
Inside the div I have fetched data with HTML SIMPLE DOM from other site. Like
<div id="data">.....</div>
It will refresh each and every time user will refresh the page. But I want something extra. What I wanna do is, refresh the div (inside which external data is fetched and added) periodically after 5 seconds.
Both the PHP SIMPLE HTML DOM script and this div is on same page.
Now I only need, any jquery or javascript code to refresh the div with data id after each 5 seconds with new data fron other site and all this without refreshing the whole page.
UPDATE:
I have used this code
$(document).ready( function() {
function getTheTime(){
$.get('http://your-domain/file.php',function(data,status){
$('#data').html(data);
});
}
var refresh = setInterval(
"getTheTime()",
5000
);
});
But the problem is very very strange, why it is not refreshing the div? Infact I have set alert for the interval but it also didn't worked. What the real problem is? Why it is not getting data from file.php and why actually it is not refreshing the div??
I am using latest jquery CDN. http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js
$(function() {
setInterval(function(){
$('#data').load('site.php');
}, 5000);
});
Definitely a job for AJAX...
Since you say you're already using jQuery, I'll walk you through the steps quickly to get an AJAX function set up and run it on an interval.
Step 1: Create a PHP file which gets the data you want to put in the DIV...
Just make a PHP file and put the code in to get the data:
<?php echo "The time is " . date('Y-m-d H:i:s');
Step 2: Set up an AJAX function to get the data from that file...
function getTheTime(){
$.get('http://yourdomain.com/ajax/getthetime.php',function(data,status){
$('#data').text(data);
});
}
(It would be possible to use the .load function instead, but it's far less flexible if you want to do anything with the data before putting it in the DIV).
Step 3: Call that function on an interval...
Next, we need to set up an interval to call the new function every 5 seconds.
$(function(){
var refresh = setInterval(
getTheTime(),
5000
);
});
Instead of using setInterval to call the function every 5 seconds, you can use simple long polling technique to refresh your div every 5 seconds. The problem with setInterval is that if the ajax request doesn't complete in specified time (5 secs here) there will be the chain of ajax requests.
function getTheTime(){
$.ajax({
type: "POST",
url: "http://your-domain/file.php",
success: function(response) {
$('#data').html(response); //update your div
},
complete: function(){
setTimeout(
getTheTime, /* Refresh time */
5000 /* ..after 5 seconds */
);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
//display you error message
},
timeout: 5000 //Timeout is necessary to prevent chaining of unsuccessful ajax request
});
}
I am going to update a small chat between two users every minute. This is already working - however I can't figure how to do an AJAX call to update the DIV containing the actual messages.
var interval
window.onload = function(){
interval = setInterval('updateMessages()', 2000);
};
function updateMessages() {
$(function () {
// UPDATE #mail_container
});
}
What´d be a proper way approaching this?
The easiest way is probably to include jQuery and make use of either its .append() or .html() methods.
eg. $("#mail_container").html("<p>Your chat message</p>");
See:
http://api.jquery.com/append/
http://api.jquery.com/html/
I've got a div that randomly shows 1 of 10 files on each pageload. I'd like this to reload on a set time interval of 8 seconds, giving me a different one of the 10 files each reload.
I've read a few of the related questions using jQuery .load as a solution but this doesn't quite work with my code since I'm not loading a specific file each time.
This is my div content:
<div id="tall-content">
<?
$random = rand(1,10);
include 'tall-files/' . $random . '.php';
?>
</div>
Thanks
Using only PHP to accomplish this is impractical. This example uses jQuery and PHP.
$(document).ready(function() {
$("#div").load("random.php");
var refreshId = setInterval(function() {
$("#div").load('random.php');
}, 8000);
$.ajaxSetup({ cache: false });
});
random.php
$pages = array("page1.php", "page2.php", "page3.php", "page4.php", "page5.php");
$randompage = $pages[mt_rand(0, count($pages) -1)];
include ($randompage);
while using PHP to generate the random content, you cannot get the div to reload that content without refreshing the entire page.
A better solution is to use AJAX. You can store that PHP code that's inside the div container as a seperate file, and use ajax to request that php file. You can also set an infinite loop to request the php file every 8 seconds. Here is a sample, but you will need to re-code it to your specification:
<script language="javascript" type="text/javascript">
<!--
function ajaxFunction(){
var ajaxRequest;
try{ajaxRequest = new XMLHttpRequest();} catch (e){try{ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");} catch (e) {try{ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");} catch (e){alert("Error: Browser/Settings conflict");return false;}}}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.getElementById('tall-content').innerHTML = ajaxRequest.responseText;
}
}
var url = "random.php";
ajaxRequest.open("GET", url, true);
ajaxRequest.send(null);
}
//-->
</script>
The only missing part is the refresh timer, since I do not program a lot in javascript I can't help you there. But the goal in this case is to create a file "random.php", put the random generator there, and use this script above to make an ajax request to random.php, which will place the output of that php script in the div container with the id of "tall-content". So really, you need to create another javascript which loops indefinitely calling the function "ajaxFunction()" and wait 8000 milliseconds .
If you want to do this while the user is sitting back in the chair on your page, the answer is javascript.
You could use this function for example.
function recrusive_timeout_function() {
setTimeout(function() {
recrusive_timeout_function();
}, 8000);
}
If you want to include a php file in that div (which outputs some html). Ajax is your friend and JQuery as a user friendly and easy to use javascript framework which handles your thinks really nice.
Can anyone please tell me how to write a small div container in HTML that refreshes its contents from the data in mysql every 5 min.
This is similar to twitter updates in some webpages which show updates as and when tweeted.
Thanks.
You can use the setInterval function to make AJAX calls:
setInterval(function() {
$('#dynamicDiv').load('DynamicDivData.php');
}, 5 * 60 * 1000); //300,000 milliseconds.
Where DynamicDivData.php connects to the database and returns the HTML to put in the <div>.
To avoid caching issues, you can append a random number in the querystring:
$('#dynamicDiv').load('DynamicDivData.php?NoCache=' + Math.random());
With Jquery
$(document).ready(function () {
$("#live").load("ajax.php");
var refreshId = setInterval(function () {
$("#live").load('ajax.php?randval=' + Math.random());
}, 3000);
});
it calls ajax.php in first load and every 3 seconds to #live div.