I have a visits.php script that automatically checks a MySQL file and displays how many total visitors have logged on.
I have a index.php script that I use as the main page of my website.
I have tried looking for code to call the script “visits.php” as a function in “index.php”, but it just doesnt work.
I have tried the same but calling from a “index.HTML” and it works.
Is there any way of calling a PHP script every 5 seconds from within another PHP script?
The method I have been looking at is setInterval(“refreshBlock();”,3000); and displaying the visits.php result in a block DIV.
Sounds like what you need is AJAX to send a request at set intervals from index.php to visits.php. Visits.php would query the database and get the data you want and then send the data back to the browser for display without refreshing the index.php.
If this isn’t what you need, then it would help if you post the code you have so far.
hi, im a beginner with AJAX, but I have been reading up on w3schools PHP AJAX/SQL examples.
I have my visits.php working fine, but need to call the script every 5 or 10 seconds.
The w3schools example uses a form select method, but i need an automatic check every X seconds.
Do you know a quick way to achieve this?
My Visits.php script is:
<?php
$con = mysql_connect(‘server-ip’, ‘username’, ‘password’);
if (!$con)
{
die('Could not connect: ’ . mysql_error());
}
mysql_select_db(“database”, $con);
$sql=“SELECT * FROM visitors”;
$sq = mysql_query($sql) or die(‘GuruMeditation - Error 03: Failure…’);
while ($line = mysql_fetch_array($sq, MYSQL_ASSOC))
{
$vis = MYSQL_RESULT($sq,0,“visits”);
}
echo $vis;
mysql_close($con);
?>
which seems to be fine, but Im having a head-ache trying to get the script to execute automatically.
Ok, so I have successfully got the code from w3schools working on my website, along with the call to my server which displays how many visitors, but at the moment I have to enter a character in the text box to refresh, or recall the data from my phpfile called vis.php. Is there a way of automating this?
BTW: The script below is run as a PHP script, not HTML.
You can use setInterval() to send the AJAX request to the server. You should check if the previous ajax request has completed before sending the next one. If it hasn’t completed, abort it first before sending the next one. The best way to avoid this situation is to set the requests’ interval large enough for them to complete in normal situations.
Hey webdev1958. thanks for your help. I have put your code to good use on my webpage.
It now works. What I was doing wrong (i think) was putting the javascript in the <head> section.
Ive moved it into the <body> section and now works a treat…
onwards and upwards thankyou heaps!!! best wishes… www.dix1975.com (house&electronica music artist)