I have a simple PHP page that sends a query to a mySQL database and displays the data onto a HTML table.
How can I get it to do this every 5 seconds? Currently it does this upon the page loading. The database will have changing data, so am trying to get the code to refresh every 5 seconds to keep the table updated.
How might I go upon doing this?
You need to use a client-side scripting language such as JavaScript to have a webpage do something after it has been served to a client.
Specifically, you will want to use timers and AJAX calls. You may also find the jQuery library useful for abstracting AJAX calls however it is not a requirement.
You need to use javascript ajax. For example ,
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText; // your div
}
}
xmlhttp.open("GET","getdatabase.php",true); //your php file
xmlhttp.send();
}
window.setInterval(function(){
loadXMLDoc();
}, 5000);
</script>
Then in html , you must have a div with specified ID(myDiv) Fpr example:
<body>
<div id="myDiv"></div>
</body>
Then in getdatabase.php you must fetch the value from the database and echo it out. For example,
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons");
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
Hope it works , see more at www.w3schools.com/
Use javascript timers. From there-on u can periodically run the SQL command to read the databases.
If this problem still arises, I can post some example code.
Related
i have following set of table rows which i have fetched from the database
echo "<td value='".$id."' style='border:double' bgcolor='" . getcolour($catc) . "' onclick = 'addValue(this.value);'>$id</td>";
this is actually a set of boxes and $id = $row['id'] is the number attached to each box. I want the mechanism like when a user clicks on the box the number attached to it should be echoed on a particular place on the webpage. MySql query and everything else works fine i have a problem with ajax code understanding i think so.
<script>
function valueAdd(str)
{
if (str=="")
{
document.getElementById("seats").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("seats").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ceckbus.php?q="+str,true);
xmlhttp.send();
}
</script>
waiting for ur help everyone!!
First I suggest that you use a javascript library in order to use Ajax, and avoid trying to fix the compatibility issues at your own. For example you could use jquery.com, it is pretty standard nowadays.
For the question part, please have a look at your echo code, there is an error at 'addValue(this.value);'
As I can understand the question, you want on the click event to have the $id. A simple fix it would be by using the innerHTML property, instead on .value:
echo "<td value='".$id."' style='border:double' bgcolor='" . getcolour($catc) . "' onclick = 'addValue(this.innerHTML);'>$id</td>";
or better on the echo you could pass the value directly to the addValue function, eg:
echo "<td value='".$id."' style='border:double' bgcolor='" . getcolour($catc) . "' onclick = 'addValue(\"" . $id . "\");'>$id</td>";
I know, I know. From the title up above, you are probably wondering what in in the world I am asking. Let me try and break this down a little easier because I am stuck and cannot figure this out. So here goes..............
I have a place on my site where a user can look at a list of news items that have been posted. All of the news items are listed in a MYSQL database and is retrieved and displayed on the page using PhP, like this:
$sql_list = "SELECT * FROM LatestMusic WHERE active = 'y' ORDER BY lm_id DESC";
$sql_list_result = mysql_query($sql_list,$connection) or die ('Could not select the List of Latest Music Entries');
$bgc = "FFC6C6";
while($list_data = mysql_fetch_array($sql_list_result)){
if ($bgc == "FFC6C6") {
$bgc = "FFFFFF";
} else {
$bgc = "FFC6C6";
}
print "<tr bgcolor=\"#" .$bgc. "\">";
print "<td align=\"center\" width=\"44\">";
print "<img src=\"/images/b_edit.png\" border=\"0\">";
print "</td>";
print "<td align=\"center\" width=\"63\">";
print "<img src=\"/images/b_drop.png\" border=\"0\">";
print "</td>";
print "<td align=\"left\" style=\"padding-left: 15px;\">";
echo $list_data[1];
print "</td>";
print "</tr>";
}
That part I get. From there, when the user click on anyone of the entries listed from the database, I need an external PHP page to load inside of a DIV on the same page without loading. I am using this coding in the header on the same page in order to achieve such a task:
<script>
function loadXMLDoc() {
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "YSMhome_LMeditform.php", true);
xmlhttp.send();
}
</script>
I can get the external page to load just fine into the DIV without the page reloading. The problem I'm having is this: The page that loads needs to be a form with form fields. When a user clicks on an entry in the list from the database, I need to pass a variable from the list (letting me know which entry they clicked on) into the external page that is loading in the DIV so that I can pre-populate the form fields with the data being sent. That is the part I cannot figure out.
If anyone can assist me with this, it would be greatly appreciated. I am new to AJAX (this is my first attempt with it), but I am willing to learn what I need to in order to get this to work.
When you call your ajax function, you need to pass it the relevant information. In your example, you should change:
onclick=\"loadXMLDoc()\"
to something like (assuming that $list_data[0] is an integer for simplicity):
onclick=\"loadXMLDoc({$list_data[0]})\"
Then in javascript, your function definition would look something like:
function loadXMLDoc(id)
and later on, you could change the url that is called to something like:
"YSMhome_LMeditform.php?id=" + id
Then you would have the ID available in "YSMhome_LMeditform.php as $_GET['id'].
I am a noob and i am trying to get this script working. It works perfectly in all browsers except IE. I have tried most of the solutions here on stackoverflow but none of them works for me. I am doing some kiddish mistake somewhere which I am unable to spot. Would request your help.
Also just to let you know the DOM Objects format of using appendchild might not work 100% correctly for me since this script basically passes values from a drop down which shows say numbers from 1 to 10 and based on those numbers it pulls up corresponding charts. So if I am viewing chart 1 then i can go ahead and select the drop down to view chart 3 as well. But if we use the appendchild property, it only allows me to see one of the charts by selecting 1 to 10 and it doesn't work unless I refresh the page. So unless deletechild is used I think it would not work, just my guess. Hence, I have commented that section out and I am using the good old method of innerhtml.
This is my JS function.
function showUser(str) {
debugger;
var xmlhttp = GetXmlHttpObject("Browser does not support HTTP Request");
if (str=="") {
document.getElementById("pairname").innerHTML="";
return;
}
/* <-- I HAVE ALREADY COMMENTED THIS OUT & am using a more robust function for this.
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
*/
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("pairname").innerHTML=xmlhttp.responseText;
//AS YOU CAN SEE THE ALTERNATIVE SOLUTION OF USING DOM OBJECTS HAS BEEN COMMENTED OUT.. SINCE THIS IS ALSO NOT WORKING IN IE FOR ME.
//var wrappingElement = document.createElement("div");
//wrappingElement.innerHTML = xmlhttp.responseText;
//document.getElementById('pairname').appendChild(wrappingElement);
}
}
xmlhttp.open("GET","getimgdetails.php?q="+str,true);
xmlhttp.send();
}
function GetXmlHttpObject(errorMessage) {
var r = false;
try { r = new XMLHttpRequest(); }// Opera 8.0+, Firefox, Safari
catch(e) {
// Internet Explorer Browsers
try { r = new ActiveXObject("Msxml2.XMLHTTP"); }// older IE
catch(e) {
try { r = new ActiveXObject("Microsoft.XMLHTTP"); }// IE 5+
catch(e) {// AJAX not possible
if(errorMessage) { alert(errorMessage); }
}
}
}
return r;
}
AND THIS IS WHERE I AM SHOWING IT
<div id="pairname"><b>Charts will be shown here.</b></div>*
AND this is the Script which receives and sends back the info. SO basically it shows 5 charts for each number 1 to 10.
$q=$_GET["q"];
Echo "<img src=mqluploads/".$q."15.gif?".time()."></img>";
Echo "<br>";
Echo "---------------------------------------------------------";
Echo "<br>";
Echo "<img src=mqluploads/".$q."60.gif?".time()."></img>";
Echo "<br>";
Echo "---------------------------------------------------------";
Echo "<br>";
Echo "<img src=mqluploads/".$q."240.gif?".time()."></img>";
Echo "<br>";
Echo "---------------------------------------------------------";
Echo "<br>";
Echo "<img src=mqluploads/".$q."1440.gif?".time()."></img>";
Echo "<br>";
Echo "---------------------------------------------------------";
Echo "<br>";
Echo "<img src=mqluploads/".$q."10080.gif?".time()."></img>";
Echo "<br>";
Echo "---------------------------------------------------------";
Echo "<br>";
Echo "<img src=mqluploads/".$q."43200.gif?".time()."></img>";
Echo "<br>";
Echo "---------------------------------------------------------";
Echo "<br>";
?>
Many many thanks in advance for your help and for reading this far. I have been struggling with this for the past one week and now finally decided to seek some help. Looking forward to your advice.
Have you checked that your php script is returning some data. Try to access getimgdetails.php?q=str (replace str with correct paremeter) directly in browser.
Also place an alert(xmlhttp.responseText) before this line:
document.getElementById("pairname").innerHTML=xmlhttp.responseText;
This will help you to debug.
I had xmlHTTPrequest GET script which was working fine, but because of server issues I had to change it to POST method. I am unable to get the data in $_POST variable. When I checked in CHROME INSPECTOR debug tool, GET Method status is 200 ok. Need help to see if the javascript is correct.
xmlHTTPrequest file:
<script type="text/javascript">
function showprodes(str2)
{
var q2 = encodeURIComponent(str2);
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
var url = "http://www.amg.in/amogtst/rateprod.php";
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send(q2);
}
</script>
<?
$result2 = mysql_query("SELECT Prod_desc FROM PRODMAST ORDER BY Prod_desc");
echo "<form name='f1'>";
echo " <span class='style3'>Gas Type </span> <select name='Proddesc' onchange=\"showprodes(this.value);\"><option value=0>Select a Product</option>";
while($nt2=mysql_fetch_assoc($result2))
{
echo "<option value='$nt2[Prod_desc]'>$nt2[Prod_desc]</option>";
}
echo "</select>";// Closing of list box
echo "</form>";
?>
Second script which updates the table as per the user selection from first php: rateprod.php file:
<?php
$q=$_POST['q2'];
$q2=mysql_real_escape_string($q);
include_once 'db.php';
mysql_query("UPDATE RATEMASTER_draft SET Prod_desc='$q2'");
?>
From looking at your AJAX code, you aren't supplying the POST variables correctly. The format for the POST string being given to xmlhttp.send() needs to be in the same format as a GET string. Trying using xmlhttp.send("q2=" + q2).
BTW, for future reference, you can use print_r($_POST) to show the contents of all POST variables. This can be very handy for debugging.
I have some main categories and subcategories of each main category..I've a dropdown list contains main category, when i choose a main category then the subcategory dropdown list shows the subcategories of that main category..
am using the following code for this, but this shows the subcategory box contains the whole page with header and footer...
<select name="main_category" id="main_category" onchange="showSubCategory(this.value)">
<option>--Select--</option>
</select>
<script type="text/javascript">
function showSubCategory(str)
{
if (str.length==0)
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert(xmlhttp.responseText);
document.getElementById("subcategory").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","index.php?main_page=getsubcategory&cid="+str,true);
xmlhttp.send();
}
</script>
in tpl_subcategory_default.php contains
<?php
$cid=$_GET['cid'];
$sql="select cd.categories_name, cd.categories_id
from " . TABLE_CATEGORIES . " c, " . TABLE_CATEGORIES_DESCRIPTION . " cd
where c.parent_id = '" . (int) $_GET['cid'] . "'
and c.categories_id = cd.categories_id
and c.categories_status= 1";
$r=mysql_query($sql);
while($row=mysql_fetch_array($r))
{
echo "<option value=$row[categories_id]>$row[categories_name]</option>";
}
?>
It's showing the whole page with header and footer because you're accessing the "page" via index.php?main_page=foo but haven't added architecture to replace the normal templating system outputs with your own page-specific output ... ie: to jump directly to the output without first calling the normal things which appear on every page.
Your question can't really be accurately answered without knowing also what you've done in the /includes/modules/pages/subcategory/header_php.php file, or if you've even created one. Chances are that the code you've put into tpl_subcategory_default.php could go into the header_php.php file mentioned above, followed by a die() statement at the end, and accomplish the same thing which you seem to be looking for.
It would be easier to answer your question fully if you supplied more information about what you've done so far.
To remove header,footer etc you can override the tpl_main_page.php. Go to this directory /includes/templates/custom template. As per your information you have created main_page=getsubcategory page. so create a folder named getsubcategory under this directory. then copy tpl_main_page.php from includes/templates/custom template/common/ and paste it in /includes/templates/your custom template/getsubcategory. Then do the below changes in tpl_main_page.php file.
if (in_array($current_page_base,explode(",",'getsubcategory')) ) {
$flag_disable_left = true;
$flag_disable_header = true;
$flag_disable_footer = true;
}