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
});
}
Related
I have a page displaying a catalogue of items on auction. Each has a button to place bids that has a timeout of 2 seconds to check if a new bid has been placed. There is also another script that checks if the minimum amount for this item has been reached. This one has a timeout of 3 seconds.
I had a timer on the page counting down until the auction closes that fired every second but this ended up blocking up the resources of the browser and everything lagged. What I ended up doing was calling this timer externally with javascript doing the actual countdown. This freed up the browser resources perfectly.
The problem I am facing is that if people are actively bidding in the last minute, it needs to recognise there is a bid-war taking place and add two minutes to the timer. I have the PHP code for this and it worked fine when the timers were on the page firing every second but now the ajax calls the timer once so the two minutes won't get added. Below is the code for the one second ajax, and secondly what I have now.
The question is, how can I get the second option to refresh the php page independantly from the main page? I realise I probably need it to run like before but that loads the browser again.
//ORIGINAL OPTION
$(document).ready(function() {
$(function worker(){
// don't cache ajax or content won't be fresh
$.ajaxSetup ({
cache: false,
complete: function() {
// Schedule the next request when the current one's complete
setTimeout(worker, 1000);
}
});
// load() functions
var loadUrl = "/lot-timer.php?lot_id=<?php echo $rsprod['lot_id']; ?>&auction_id=<?php echo $row['auction_id']; ?>&eye=<?php echo $i; ?>";
$("#lot-timer<?php echo $rsprod['lot_id']; ?>").load(loadUrl);
// end
});
});
//SECOND OPTION
$(document).ready(function() {
$.ajax({
type: 'POST',
data:$(this).serialize(),
dataType: 'html',
url: "/lot-timer.php?lot_id=<?php echo $rsprod['lot_id']; ?>&auction_id=<?php echo $row['auction_id']; ?>&eye=<?php echo $i; ?>",
success: function (d) {//begin success
//add the pending message to a div on the page
$("#lot-timer<?php echo $rsprod['lot_id']; ?>").html(d);
}//end success
});
});
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 have a website, and in the navigation header, I have a player count, for the people who are currently online (On an external server). The count is outputted as a raw number generated by PlayersOnline.php, and I just include that.
How would I have this page update the player count every X seconds without refreshing the page?
You can use Javascript and jQuery to solve this:
$(function() {
updateCounter();
});
function updateCounter() {
$.ajax({
url: 'yourScript.php',
success: function(output) {
$('#yourCounterElementID').text(output);
},
complete: function() {
setTimeout(updateCounter(), 5000);//run again in 5 seconds
}
});
}
I would like one DIV on my page to automatically refresh after 10 minutes. I don't want to reload the entire page, just the one part.
This is the PHP that I am using:
function fblikes() {
$pageID = $_GET['id'];
$pagename = json_decode(file_get_contents('http://graph.facebook.com/' . $pageID));
echo $pagelikes->likes;
}
And this is what I want to be refreshed automatically:
<div>
<span><?php fblikes(); ?></span>
</div>
Can somebody help me with this please?
Quoting myself:
You cannot 'reload a div'. A div is just a single element on an
entire webpage, and on its own it has no URL it was loaded from, so it
cannot be reloaded. You can set/replace the contents of a div with an
Ajax call, but that's definitely not 'reloading' - you'd need to
explicitly define the URL to load its new content from.
You need to write some Javascript, use setTimeout to schedule a function for execution in 10 minutes, and then use an Ajax call to retrieve JSON or HTML data that is then either parsed or placed in the relevant span element.
In your very specific situation you can make your own life easier by using the Facebook clientside Javascript API, and just issue a FB.api(...) call every 10 minutes since that appears to be what you want.
use JQuery/Ajax for that.
Example:
function reloadDiv() {
$.ajax({
url: URL_TO_YOUR_PHP_SCRIPT,
type: 'get',
success: function(result) {
if (result) {
$('#YOUR_DIV').html('<span>' + result + '</span>');
}
}
});
}
and use setTimeout to reload this div every 10 minutes like:
setInterval("reloadDiv()", 600000); // 60 * 1000 * 10
I am programming an online PHP-based fantasy pet simulation game. I am not very familiar with AJAX, so please keep this in mind when answering.
On pet pages, I would like users to be able to feed/water/play with their pets without needing to reload the entire page - that's why I'm using AJAX. Here's what I have so far:
Working Script
$(function() {
$(".petcareFood").click(function(event) {
event.preventDefault();
$("#petcareFood").load($(this).attr("href"));
});
});
$(function() {
$(".petcareWater").click(function(event) {
event.preventDefault();
$("#petcareWater").load($(this).attr("href"));
});
});
$(function() {
$(".petcarePlay").click(function(event) {
event.preventDefault();
$("#petcarePlay").load($(this).attr("href"));
});
});
</script>
Working HTML
<a class=\"petcareFood\" href=\"petcare.php?pet=#&action=#\">Feed Your Pet</a>
<a class=\"petcareWater\" href=\"petcare.php?pet=#&action=#\">Water Your Pet</a>
<a class=\"petcarePlay\" href=\"petcare.php?pet=#&action=#\">Play With Your Pet</a>
NOW, everything that I listed above works like a charm! This is my problem: I want those links to also update another DIV - the one which contains updated status bars showing how hungry/thirsty/unhappy their pet is. Currently, I am doing that like this:
The Almost Working Script
$(function() {
$(".petcareFood").click(function(event) {
event.preventDefault();
$('#petcareHunger').load('ajax/hunger.php?pet=#');
});
});
$(function() {
$(".petcareWater").click(function(event) {
event.preventDefault();
$('#petcareThirst').load('ajax/thirst.php?pet=#');
});
});
$(function() {
$(".petcarePlay").click(function(event) {
event.preventDefault();
$('#petcareMood').load('ajax/mood.php?pet=#');
});
});
The script above makes it so that when a user clicks one of the HTML links, it updates two DIVS (one DIV containing the message displayed when a user feeds/waters/plays with their pet, and the other containing the status bar). Now... that seems all fine well and good, BUT... if both scripts update at exactly same time, then the PHP that handles the status bar is not updated - it's still retrieving old information.
My question to all of you is: Is there any way that I can delay running the second set of script (so that it will update after the PHP makes changes to MySQL)?
I tried inserting this before "the almost working script":
setTimeout(function() {
$('#petcareMood').load('ajax/mood.php?pet=#');
}, 2000);
However, it doesn't work. Well - it does, but just once. Users need to play with their pets at least 3 times a day to achieve 100% happiness, and so delaying the second DIV only once doesn't cut it for me. When I tried adding the same script multiple times, it just stopped working all together. What can I do?!
If you'd like to see screen shots of how things are working, please just ask. I will be happy to provide them upon request.
Thank you in advance!
Instead of a hardcoded delay time, you maybe could use the callback function of the first ajax action:
//trigger first ajax
$("#petcarePlay").load($(this).attr("href"), function(){
//trigger second ajax call, when first is completed
$('#petcareHunger').load('ajax/hunger.php?pet=#');
});
see http://api.jquery.com/load/
You could use the complete parameter to specify a callback function that gets executed when the request completes. Then from within the callback, execute another request which actually updates the divs.
Example:
$(".petcareWater").click(function(event) {
event.preventDefault();
$("#petcareWater").load($(this).attr("href"), function(response, status, xhr) {
// code here to make another request for stats
}
});
Alternatively, you could have the initial URLs return some JSON data that contain the updated stats so when a person does something to/with their pet, it returns all the stats so you can immediately update the div's all with one call rather than having to make a secondary call for the data.
I'm not sure, but i think the ajax constructor is better for your purpose http://api.jquery.com/jQuery.ajax/.
There you can set that the AJAX will be synchronous(It will wait to finish the AJAX callback )
Here is a few theory about it :)
http://javascript.about.com/od/ajax/a/ajaxasyn.htm
Instead of setTimeout, use setInterval. When it's no longer needed, you can kill it using clearInterval.
setInterval will execute a given function every n milliseconds.