Automatically run a PHP script every X seconds without refreshing the page - php

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
}
});
}

Related

PHP / Ajax Page Loading / Timeouts

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
});
});

Materialize.css Dynamic Modals + Ajax glitching out

I've recently started using materialize.css in my projects and it's been great. However, in my latest website, I tried creating dynamic modals with ajax gathered data.
The modals generate correctly but a weird glitch appears. After generating the modal it should automatically open, but it only opens after you click three times the trigger and it generates three modals (you can test it here).
Here's the code:
$(".champion-card").click(function() {
var champion = $(this).find(".card-title").html();
var champion_id = champion_id = champion.replace(/ /g,"-").replace('.', "")+'Modal';
$.ajax({
type: 'POST',
url: 'getdata.php',
data: { scripts: champion },
success: function(data) {
$("body").append('<div id="'+champion_id+'" class="modal"><div class="modal-content"><h4>Scripts - '+champion+'</h4><div class="row"><ul class="list">'+data+'</ul></div></div></div>');
}
});
$('#'+champion_id).modal('open');
$('#'+champion_id).modal({
complete: function() {
$(this).remove();
}
});
});
'getdata.php' only echoes a text containing the data posted.
http://materializecss.com/modals.html says opening a modal is done by the code:
$('#modal1').modal('open');
If I remember correctly, before it was .leanModal(), but I don't think that's a cause. The frustrating thing is that it opens after 3 clicks, generating 3 modals with the same id.
I couldn't find what's wrong and I though maybe the community can help. The are no errors received.
Thanks!

jQuery Ajax: Cannot highlight text from ajax result

I am trying to display all employee name from database and automatically display the newly added name without page refresh. I used setInterval to get the data every 1 second so the displayed data is always updated.
My problem is, I cannot highlight a text from the ajax result because it refresh the ajax result every 1 second. So how can I be able to do that?
setInterval(function(){
$.ajax({
type: 'GET',
url: url+'dashboard/getLastPost',
success: function(data) {
$('.lastPost').html(data);
}
});
}, 1000);
How about
success: function(data) {
$('.lastPost').css("color","red");
$('.lastPost').html(data);
}

Refresh div on same page with external fetched data

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
});
}

jquery ajax load with delay - php div rotation

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

Categories