Jump to content

Recommended Posts

Hi All,

 

for every person the page should get data from mysql and display it on the page without any onchange, onclick or input... i have a form where persons make entries which are submitted to mysql and i want to see them all in another page. So it simply will get data from mysql every second without f5.

 

is this possible and can you give me a lead?

 

thanks...

Link to comment
https://forums.phpfreaks.com/topic/169492-auto-refresh-without-any-input/
Share on other sites

Thanks for the reply.

 

Assume i have a table in mysql like -->

 

id  inputvolume  name 

0    5              john

1    4              mike

2    3              john

3    5              mike

...

 

and i have a page which should connect to database and read it-->

 

name    volume

john      echo ...

mike      echo...

 

how can i do that the page will connect to database and read the data?

don't misunderstand me, i can make the connection via php and read the data this is no problem via ususal meta refresh but i don't have a clue how its done via ajax...

A simple starting point would be something like this

 

try it in its own file and it should update every 5 seconds, just replace the "results" line with a database query etc and you should get the idea

 

<?php
if(isset($_GET['Action']))
{
switch($_GET['Action'])
{
	case "getData":
		echo "results: ".time(); //whatever
	break;
}
die;
}

?>
<script language="javascript">
function ajaxFunction(ID, action)
{
   var loaderphp = "<?php echo $_SERVER['PHP_SELF'] ?>";
   
   var xmlHttp;
   try
    {
      // Firefox, Opera 8.0+, Safari
      xmlHttp=new XMLHttpRequest();
    }catch(e){
      // Internet Explorer
      try
      {
         xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
      }catch(e){
         try
         {
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
         }catch(e){
            alert("Your browser does not support AJAX!");
            return false;
         }
      }
   }
    xmlHttp.onreadystatechange=function()
   {
      if(xmlHttp.readyState==4)
        {
         document.getElementById(ID).innerHTML = xmlHttp.responseText;
        }
   }
    xmlHttp.open("GET", loaderphp+"?Action="+action,true);
    xmlHttp.send(null);
}
setInterval( "ajaxFunction('test','getData')", 5000); //execute function doSomething(), every 5 seconds


</script>
<div id="test">
</div>

 

Hope it helps

I wrote this dead quick and it works perfectly provided you have the table in the datbase setup correctly.

 

All you need to do is include the script and possibly change the div id within the div tag AND within the JS. In addition youll have to setup the PHP to connect to the database.

 

 

// PHP called "ajaxphp.php"

<?php

$dbhost = "";
$dbuser = "";
$dbpass = "";
$dbname = "";

$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die("Cannot connect to mysql server");
mysql_select_db($dbname) or die("Cannot select database");

if($conn){

	$gInfo = mysql_query("SELECT * FROM `table_name` ORDER BY `id` DESC LIMIT 20");

	print "<table cellspacing=\"0\" cellpadding=\"0\">";
	print "<tr><th>name</th><th>volume</th></tr>";
	while($Info = mysql_fetch_assoc($gInfo)){
		print "<tr><td>".$Info['name']."</td><td>".$Info['inputvolume']."</td></tr>";
	}
	print "</table>";

}

?>

 

 

// JAVASCRIPT called ajax.js

// AJAX REQUEST
function httpRequest(){
var httpRequest = null;
try { httpRequest = new XMLHttpRequest(); }
catch(e){
	try{httpRequest = new ActiveXObject("Msxml2.XMLHTTP");}
	catch(e){httpRequest = new ActiveXObject("Microsoft.XMLHTTP");}
}
return httpRequest;
}

var t;
function load_data(){
var http_request = httpRequest();
var object_area = document.getElementById('object_area');
var url = "ajaxphp.php";
http_request.open("GET", url, true);
http_request.onreadystatechange = function(){
	if(http_request.readyState == 4){
		object_area.innerHTML = http_request.responseText;
	}
}
http_request.send(null);
t = setTimeout(load_data, 1000);
}

document.onLoad = load_data();

 

// PHP/HTML PAGE called whatever you want but just make sure you include the script.

<html>
<head>
<script src="ajax.js" type="text/javascript"></script>
</head>
<body>
<div id="object_area">

</div>
</body>
</html

 

I prefer this way to the one suggested above because the "set interval" doesnt execute straight away on load it waits 5 seconds then executes where as this executes then waits a second if that makes sense?

  • 2 months later...

Fantastic script/s MadTechie! many thanks.

just what I was after to display live weather data on our company intranet. The data is logged to our Mysql server and I have made a nice wee page to display some polar jpgraph plots etc etc. Well happy. (or at least till I fired up Mr gates IE)!!

Trouble is it will not work on IE6 and since IE6 is still very much alive throughout our company. I have tried to modify your script to enable cross browser support but to no avail, any help would be greatly appreciated. My Ajax / Javascript is not great and Google is getting impatient with me!! Here is what I have done to try to include additional cross browser support. The error I am getting is " 'object_area' is null or not an object".  On first load it will get the values from the database but will not update / refresh as id does so well in firefox!

 

// AJAX REQUEST

// function to create an XMLHttpClient in a cross-browser manner
function httpRequest() {
      var httpRequest = null;
      try {
          // Mozilla / Safari / IE7
          httpRequest = new XMLHttpRequest();
      } catch (e) {
          // IE
          var XMLHTTP_IDS = new Array('MSXML2.XMLHTTP.5.0',
                                     'MSXML2.XMLHTTP.4.0',
                                     'MSXML2.XMLHTTP.3.0',
                                     'MSXML2.XMLHTTP',
                                    'Microsoft.XMLHTTP' );
          var success = false;
          for (var i=0;i < XMLHTTP_IDS.length && !success; i++) {
              try {
                   httpRequest = new ActiveXObject(XMLHTTP_IDS[i]);
                      success = true;
                } catch (e) {}
          }
          if (!success) {
              throw new Error('Unable to create XMLHttpRequest.');
          }
     }
     return httpRequest;
}

var t;
function load_data(){
   var http_request = httpRequest();
   var object_area = document.getElementById('object_area');
   var url = "ajax_php.php";
   http_request.open("GET", url, true);
   http_request.onreadystatechange = function(){
      if(http_request.readyState == 4){
         object_area.innerHTML = http_request.responseText;
      }
   }
   http_request.send(null);
   t = setTimeout(load_data, 1000);
}

document.onLoad = load_data();

Hi

 

Had a play with a very simple page and with your code and what appears to be happening is that the onLoad event is being triggered before the page has finished loading. I get the same with Opera (9.63) and FF (3.5.3), and possibly Chrome, just that they are not obvious about it.

 

Not sure why this is happening. Strangely taking out your onload event and putting it into the body tag (<body onLoad="load_data()">) might fix the problem. Also changing your onLoad event to call the timer does as well (but I suppose that assumes the body has loaded within a second). Another thing that appears to fix it is to change the script to put the assignment of the object_area variable within the if for http_request.readyState == 4.

 

This doesn't make sense to me as onLoad shouldn't fire until the document has finished loading.

 

All the best

 

Keith

 

All the best

 

Keith

Thanks Kickstart,

I have tried what you suggest but this makes no difference! I shall continue hunting for a solution!!

I am not sure if the error I receive in IE (null or not an object) is even the problem as I now notice I get it in Firefox also!

 

colsieb

Hello again Kickstart! thanks again for your help.

I tried both solutions and neither appeared to work, perhaps i'm not doing it right!

I have a basic copy of the page here, http://colinbonner.plus.com/weather.php.

the js

http://colinbonner.plus.com/ajax.js

the phpscript i'm executing with the js

http://colinbonner.plus.com/live_weather.txt

the main php

http://colinbonner.plus.com/weather.txt

 

many thanks!

 

 

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.