Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Javascript calling PHP into variable - almost working. Can you help?

Status
Not open for further replies.

mrcheeky

Programmer
Sep 11, 2008
6
US
Hi,

I'm stuck, but it's almost working!

From a html page, my javascript calls a server-side php script. The php reads a value from a server-side .txt file and passes it back as a javascript variable. This all works fine.

However, I want it to loop within a javascript function every 5 seconds. The function does other stuff, so looping within this function is essential (I've simplified it in the example below).

Any advice would be appreciated, I don't want to learn Ajax quite yet as my brain's already full with trying to learn php/javascript!

I've got the following in my .txt file:


Code:
graph_counter1 81
This gets pulled into an array by my .php code:


Code:
<?php
    Header("content-type: application/x-javascript");
    //read html param to get graph_number
    $graph_number = $_GET["graph_request"];
    //open datafile and create array of each line
    $fp=fopen('C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\frame_realtime.txt',"r");
    while(!feof($fp)) {
    $line=fgets($fp);
    list($key,$value) = split("[[:space:]]+",$line);
    $array[$key] = $value;
    }
    fclose($fp);
    //send output back to calling page
    echo 'var random_number="'.$array[$graph_number] .'";';
?>
Finally, I've got the following in my .html page, which calls the .php:


Code:
<html>
<head>
<script type="text/javascript" src="realtime_read_values.php?graph_request=graph_count  er1"></script>
<script type="text/javascript">  
function AddBar1()
{
document.write(random_number);
setTimeout('AddBar1()', 5000);
}
</script>
</head>
<body onload="AddBar1()">
</body>
</html>
(Ignore the gap between count and err1 in this last example - the form is playing games..)

This prints the number '81' on my html page, and works fine for the 1st load. After this is doesn't go through the loop anymore so the number remains the same. I've tried many ways to get the php call into the loop but it won't work.

I need help in working out how to put the .php call INSIDE the looping function.

thanks,
Will
 
Your look doesn't re-load the script file, so therefore the variable is always the same.

You could do this several ways:

- Delete the script element and re-attach it (document.createElement, etc)

- Use AJAX

- Some other way I've not thought of.

Using the first method, you'd have to wait for the script load to before assuming you can read the variable. The AJAX method wouldn't suffer from this restriction.

Hope this helps,
Dan



Coedit Limited - Delivering standards compliant, accessible web solutions

[tt]Dan's Page [blue]@[/blue] Code Couch
[/tt]
 
Thanks for the reply.

Unfortunatlely I'm a novice and still learning this stuff. Do you mind pasting an example of code that would work? I've been reading up for days on this!
 
Evening Will,

Here is a stand-alone test file I whipped up to show how you might do this (it's a PHP file - so must be served up as such):
Code:
<?
	if (isset($_GET['xhttp'])) {
		$counter = date("d M Y h:m:s");
		echo $counter;
	} else {
?>
<html>
<head>
	<title>Test some XHTTP</title>
	<script type="text/javascript">
		function getHTTPObject() {
			var xmlhttp;
			/*@cc_on
			@if (@_jscript_version >= 5)
				try {
					xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
				} catch (e) {
					try {
						xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
					} catch (E) {
						xmlhttp = false;
					}
				}
			@else
				xmlhttp = false;
			@end @*/
			if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
				try {
					xmlhttp = new XMLHttpRequest();
				} catch (e) {
					xmlhttp = false;
				}
			}
			return xmlhttp;
		};
	
		function fetchData() {
			http = getHTTPObject();
			http.open('get', "<?= $_SERVER['SCRIPT_NAME']; ?>?xhttp=true", true);
			http.onreadystatechange = function() {
				if (http != null && http.readyState == 4) {
					document.getElementById('displayCounter').innerHTML = http.responseText;
				}
			};
			http.send(null);
		};
		
		function initPage() {
			http = null;
			pageTimerHandle = setInterval('fetchData()', 2000);
		};
		
		window.onload = initPage;
	</script>
</head>

<body>
	<h1>Test page</h1>
	<p>This page is using AJAX to update the current time every two seconds.</p>
	<div id="displayCounter"><?= date("d M Y h:m:s"); ?></div>
</body>
</html>
<? } ?>
It will display the HTML portion on initial render (and whenever you refresh the page), but if you request the file using a particular GET parameter, then it returns the data (which could be your counter - but is the current time instead). This is essentially all there is to it!

Hope this works for you...

Cheers,
Jeff

[tt]Jeff's Blog [!]@[/!] CodeRambler
[/tt]

Make sure your web page and css validates properly against the doctype you have chosen - before you attempt to debug a problem!

FAQ216-6094
 
Thanks very much BabyJeffy.

I'll keep this in mind in case I need to turn to Ajax. However I'm trying to avoid it for now until I've started studying it. In the meantime, I'm trying to do this in Javascript. Any ideas on this?
 
...Any ideas on this?
Use AJAX - it is using javascript. It's also a much more preferred (and better understood) mechanism for this kind of activity.

Of course there are other solutions (as Dan points out above), including using a hidden iframe (and refreshing the source to get an AJAX-like result)... but it's certainly a pain to implement (compared to using AJAX).

Take 5 minutes to check out that code and see how it will work for you (you don't even have to bother looking at how the getHTTPObject function works - just use it and look at how it is used. It took me a lot longer than 5 minutes to write it (in such a way that it would have meaning for your solution).

Cheers,
Jeff

[tt]Jeff's Blog [!]@[/!] CodeRambler
[/tt]

Make sure your web page and css validates properly against the doctype you have chosen - before you attempt to debug a problem!

FAQ216-6094
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top