...

View Full Version : I was going to use php, but they told me I needed java



cowkiller6
07-02-2005, 05:04 PM
Any help would be nice.

I want to make a box on my site that shows a current number for all site members. This number is stored in a mysql table, and I need it to update automatically when it is changed.

I started asking the php guys, but they told me I needed java to make it update without the user updating their page.

Is there a simple java code to do this?

This is more in depth:

http://www.codingforums.com/showthread.php?p=328396#post328396

Thanks

vwphillips
07-02-2005, 05:46 PM
think you need to look at

http://www.i18nguy.com/markup/metatags.html

no Cache

cowkiller6
07-02-2005, 06:30 PM
Thank you for pointing me in the right direction.

I am now thinking I will just display the value as text by taking it from mysql and making it a php variable, then make it so the page cannot be cached so that when they refresh it will not be a saved/old number.

It is very important the users see what the current number is. The above plan I wrote will make it so the number is current from when they refresh the page, but I would like it so that the number can update on the page without the refreshing the page.

I could make the entire page automatically refresh, but is there anyway to only have the value of the number update every second, or everytime it changes?

As I typed that I wanted the number to change with out the page refreshing, I discovered the plan at the top of using php wouldn't work b/c as someone told me in:

http://www.codingforums.com/showthread.php?p=328323#post328323

"php is a static language, so you cannot create new variables to send until the users page updates."

Any ideas?

Thanks

Edit: Is this even possible to do with javascript?... Query a mysql table for a value and display it everytime it changes. Because I need the number amount stored in the database to be read and updated if changed, but I thought php was the only thing that can query the database, and it can only do that by refreshing the page.

Edit: edit: I found this page:

http://www.webdeveloper.com/forum/showthread.php?t=70054

Where if I understood the guy, he wasnted to do the exact same thing as me,(load text from mysql dynamicly without the page refreshing).

The other people pointed him to: XMLHttpRequest

Can anyone else verify if this is what I want? (XMLHttpRequest)

slammer
07-02-2005, 07:19 PM
xmlhttprequest is the way to go, if u want to update only a certain part of a page n not refresh the entire page.

cowkiller6
07-02-2005, 07:35 PM
Ok, thanks. I am trying to learn it right now...

Thank you

Skyzyx
07-02-2005, 07:59 PM
Step 1: Make sure that all your MySQL stuff is working (which I'm sure it is)

Step 2: Write a PHP function that reads the value from the table and returns the value when you call the function.

Step 3: Use the uber-simple Sajax (http://www.modernmethod.com/sajax/) library to have the value auto-update every 60 seconds or so.

Oh, so simple.

cowkiller6
07-02-2005, 09:37 PM
Thank you for that list. I am now on step 3.

However, I have no idea what to do with SAJAX. I downloaded it, and have pulled up the SAJAX.php file that was in the php folder, however I do not understand how I can use this to make the value autoupdate (I need it for every second or less).

Thanks

jscheuer1
07-02-2005, 10:55 PM
I just visited the Sajax library page and, without javascript enabled, their multiplier doesn't work. So, I figure javascript would be a fine substitution for anything they have. I also had some other thoughts on this topic. If cowkiller6 puts his code from step 2:
Step 2: Write a PHP function that reads the value from the table and returns the value when you call the function.on a separate page (let's call it count.php) displayed on his page(s) through an iframe or in a frame. He should be able to use a meta tag on count.php:
<META HTTP-EQUIV = "REFRESH" CONTENT = "1">so that it reloads every 1 second. Finally, he could include a script in the head of count.php:
<script type="text/javascript">
setTimeout("window.location.href=window.location.href",750)
</script>This will reload the page every 3/4 second, making the meta tag a backup for non javascript enabled browsers.

Skyzyx
07-02-2005, 11:08 PM
...without javascript enabled, their multiplier doesn't work.
Well, duh. It's an Ajax library. (didn't mean to be rude there :) ).

If you go through the instructions at http://www.modernmethod.com/sajax/faq.phtml , it walks you through how to make your PHP function (from step 2) accessible from JavaScript, which you can then write to an element (using innerHTML) every so-many milliseconds.

This way, you don't have to refresh the page constantly (which is a horrible, horrible, horrible practice), and the counter stays up-to-date constantly.

cowkiller6
07-02-2005, 11:14 PM
Ok, that will help me. I will try it all out in around 2 hours when I get home.

thanks

cowkiller6
07-03-2005, 02:21 AM
Well, duh. It's an Ajax library. (didn't mean to be rude there :) ).

If you go through the instructions at http://www.modernmethod.com/sajax/faq.phtml , it walks you through how to make your PHP function (from step 2) accessible from JavaScript, which you can then write to an element (using innerHTML) every so-many milliseconds.

This way, you don't have to refresh the page constantly (which is a horrible, horrible, horrible practice), and the counter stays up-to-date constantly.

Well, I still do not really understand the Sajax stuff. However I think I manually did whatever it does. Now I have: an html page that when you perform an action it does the xmlhttprequest function

example: onblur="updateCityState();"

This function uses a php file and gets the current number from the database.

Now, I need to change the way the function is called. Removing the onblur, and making it do the function every... say .75 seconds.

You told me to:

"then write to an element (using innerHTML) every so-many milliseconds"

Is there a simple way to do this given my functions name is function updateCityState()???

Thank you!

Harry Armadillo
07-03-2005, 05:20 AM
I'm all for xmphttprequests, but for something this small I think you'd be better of with dynamic script elements.

Here an example of how it works:
test.html
<html>
<head>

<script id="dynamic_script" src="update.js" type="text/javascript"></script>

<script type="text/javascript">

function update(){
var old=document.getElementById("dynamic_script");
var s=document.createElement("script");
s.id="dynamic_script";
s.type="text/javascript";
s.src="update.js?"+new Date().getTime();
old.parentNode.replaceChild(s,old);
}

setInterval("update()",1000);

</script>

</head>
<body>
<div id="out">&nbsp</div>
</body>
</html>
update.js
if(document.getElementById("out"))
document.getElementById("out").firstChild.nodeValue=Date();
The static .js file I've used is pretty pointless -- in reality you'd set the src to point to a php script that grabbed your value from the db and inserted that value where I currently have Date(). This nice thing about this technique is that it doesn't require ActiveX to work with IE. And the freshly fetched script element simply runs its content script as soon as it loads. No waiting around like with synchronous xmlhttprequests, no messy callback functions like with async xmlhttprequests.

If you want to send data to your server, you can add it to the query part of src URL (I've used a timestamp to eliminate caching); if you want to change more of the page, return more script.

cowkiller6
07-03-2005, 06:27 AM
I got it to continuously update by adding the line:

setInterval("updateCityState()",1000);

updateCityState is my function.
However, doing it this way, it updates once every second, but it blinks. Is there another way to do this so it doesn't blink. Also, I tried the above approach and got it to show the date but at the bottom of the screen in the toolbar it says transfering data to... and blinks like that.

So, is there anyway to make this update without blinking. When I change the time from 1000 to about 100, you cannot even see the number b/c it blinks too fast.

This is my html file:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>ZIP Code to City and State using XmlHttpRequest</title>
<script language="javascript" type="text/javascript">
var url = "getCityState.php"; // The server-side script
function handleHttpResponse(){ // Split the comma delimited response into an array
results = http.responseText;
document.getElementById('state').value = results;
}
function updateCityState() {
http.open("GET", url, true);
http.onreadystatechange = handleHttpResponse;
http.send(null);
}
setInterval("updateCityState()",1000);


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;
}
var http = getHTTPObject(); // We create the HTTP Object
</script>
</head>
<body>
<form action="post">
<p>
ZIP code:
<input type="text" size="5" name="zip" id="zip" onblur="updateCityState();" />
</p>
City:
<input type="text" name="city" id="city" />
State:
<input type="text" size="2" name="state" id="state" />
</form>
</body>
</html>

and this is the php file:


<?php
/**
* Connects to the database.
* Return false if connection failed.
* Be sure to change the $database_name. $database_username , and
* $database_password values to reflect your database settings.
*/
function db_connect() {
$database_name ='----'; // Set this to your Database Name
$database_username ='-----'; // Set this to your MySQL username
$database_password ='-----'; // Set this to your MySQL password
$result = mysql_pconnect('localhost',$database_username, $database_password);
if (!$result) return false;
if (!mysql_select_db($database_name)) return false;
return $result;
}
$conn = db_connect(); // Connect to database
if ($conn) {
$query = "SELECT * FROM Bank WHERE id = '1'";
$result = mysql_query($query,$conn);
$count = mysql_num_rows($result);
if ($count > 0) {
$city = mysql_result($result,0,'amount');
}
}
if (isset($city)) {
$return_value = $city;
}
else {
$return_value = "invalid"; // Include Zip for debugging purposes
}
echo $return_value; // This will become the response value for the XMLHttpRequest object
?>

Thank you

Harry Armadillo
07-03-2005, 06:47 AM
Echo the value into the javascript

if(document.getElementById("out"))
document.getElementById("out").firstChild.nodeValue=<?php echo $amount; ?>;
An external javascript file doesn't have the <script ... > and </script> tags inside it.

It's also worth setting the proper content-type header at the beginning of your script:

header("Content-type: text/javascript");


<?php
header("Content-type: text/javascript");

/**
* Connects to the database.
* Return false if connection failed.
* Be sure to change the $database_name. $database_username , and
* $database_password values to reflect your database settings.
*/
function db_connect() {
$database_name ='test'; // Set this to your Database Name
$database_username ='---------'; // Set this to your MySQL username
$database_password ='---------'; // Set this to your MySQL password
$result = mysql_pconnect('localhost',$database_username, $database_password);
if (!$result) return false;
if (!mysql_select_db($database_name)) return false;
return $result;
}
$conn = db_connect(); // Connect to database
if ($conn) {
$query = "SELECT * FROM Bank WHERE id = '1'";
$result = mysql_query($query,$conn);
$count = mysql_num_rows($result);
if ($count > 0) {
$amount = mysql_result($result,0,'amount');
}
}
?>
if(document.getElementById("out"))
document.getElementById("out").firstChild.nodeValue=<?php echo $amount; ?>;

jscheuer1
07-03-2005, 06:59 AM
Looks like cowkiller6 is getting things sorted out with lots of help, just wanted to reassure Skyzyx that you have to do more than tell me that something that sounds like a kitchen cleanser, is javascript, to piss me off. :cool:

cowkiller6
07-03-2005, 04:03 PM
Thanks everyone for the help!

Using your method Harry, at the bottom in the toolbar, it always flashes connecting to site,done,connecting to site,done. Is there a way to get rid of this?

I got it working with xmphttprequests, its just that to make it update, I added the line:


function updateCityState() {
http.open("GET", url, true);
http.onreadystatechange = handleHttpResponse;
http.send(null);
}
setInterval("updateCityState()",1000);

Doing it this way, it does refresh, but everytime it refreshes the text blinks. If I set it to a lower interval than 1000, it blinks faster and faster until it is invisible.

I am sure that I am doing this the wrong way to make it update. However I did not understand what I should do when you told me to:


go through the instructions at http://www.modernmethod.com/sajax/faq.phtml , it walks you through how to make your PHP function (from step 2) accessible from JavaScript, which you can then write to an element (using innerHTML) every so-many milliseconds.

I already have the PHP function that the javascript calls, so I THINK I am at the write to an element using innerHTML. Could someone clarify what this means? I have looked up innerhtml, but I don't understand it...


Thank you

jscheuer1
07-03-2005, 09:16 PM
document.getElementById('id').innerHTML=varIt doesn't really matter how you get the element, I just used getElementById as an example, it is the most often used in regular javascript coding. In the above, id is the unique id of the element you are accessing:
<p id="users"></p>Then you would use:
document.getElementById('users').innerHTML=varVar is the name of a variable you have prepared elsewhere in your code, before executing this line. It could be mixed with a literal:
document.getElementById('users').innerHTML=var+' Users are online'

cowkiller6
07-03-2005, 10:36 PM
I am confused now, is the above explaining how to write it to an element (using innerHTML) every so-many milliseconds?

I have a code where it is getting the mysql database value and returning, however I just need to make this code update every second.

This is my code for update.html


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>ZIP Code to City and State using XmlHttpRequest</title>
<script language="javascript" type="text/javascript">
var url = "getCityState.php"; // The server-side script
function handleHttpResponse(){ // Split the comma delimited response into an array
results = http.responseText;
document.getElementById('city').value = results;
}
function updateCityState() {
http.open("GET", url, true);
http.onreadystatechange = handleHttpResponse;
http.send(null);
}


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;
}
var http = getHTTPObject(); // We create the HTTP Object
</script>
</head>
<body>
<form action="post">
<p>
ZIP code:
<input type="text" size="5" name="zip" id="zip" onblur="updateCityState();" />
</p>
City:
<input type="text" name="city" id="city" />
State:
<input type="text" size="2" name="state" id="state" />
</form>
</body>
</html>


This is my code for getCityState.php :


<?php
/**
* Connects to the database.
* Return false if connection failed.
* Be sure to change the $database_name. $database_username , and
* $database_password values to reflect your database settings.
*/
function db_connect() {
$database_name ='test'; // Set this to your Database Name
$database_username ='-----'; // Set this to your MySQL username
$database_password ='-----'; // Set this to your MySQL password
$result = mysql_pconnect('localhost',$database_username, $database_password);
if (!$result) return false;
if (!mysql_select_db($database_name)) return false;
return $result;
}
$conn = db_connect(); // Connect to database
if ($conn) {
$query = "SELECT * FROM Bank WHERE id = '1'";
$result = mysql_query($query,$conn);
$count = mysql_num_rows($result);
if ($count > 0) {
$city = mysql_result($result,0,'amount');
}
}
if (isset($city)) {
$return_value = $city;
}
else {
$return_value = "invalid"; // Include Zip for debugging purposes
}
echo $return_value; // This will become the response value for the XMLHttpRequest object
?>

ty

jscheuer1
07-04-2005, 12:04 AM
No, you looked like you already knew how to run a function every so often:

function updateCityState() {
http.open("GET", url, true);
http.onreadystatechange = handleHttpResponse;
http.send(null);
}
setInterval("updateCityState()",1000);My previous post was just to demonstrate how to access an element and write to its innerHTML for whatever use you like in your code. I also suggested you already have the text available in a variable and use that.

cowkiller6
07-04-2005, 12:20 AM
Ok, thanks. Is there another way to update the function though? My current one makes the number blink when it updates.

cowkiller6
07-04-2005, 12:56 AM
You can see what I mean here:

http://update123.tk/

Harry Armadillo
07-04-2005, 05:06 AM
I clicked your link, got a popup warning, and I decided that I'm done with this thread.

cowkiller6
07-04-2005, 05:35 AM
When you click it, it opens the website in a new window. Thanks for your help though!

jscheuer1
07-04-2005, 09:01 AM
What browser are you using? In IE I get a value of 20 and an error that says:

Line: 8
Char: 1
Error: the data necessary to complete this operation is not yet available
URL: http://techgearfree.com/update.html

It continues to update however.

In Firefox it works as you say with blinking. My guess is that the blinking is FF's way of saying:

the data necessary to complete this operation is not yet available.

I'd try something like (from your code addition in red):
results = http.responseText;
if (results!=='')
document.getElementById('city').value = results; That should take care of the blinking in FF and other Mozilla based browsers. Not sure how to get rid of the error in IE but, it works and doesn't blink in IE.

orhor
07-04-2005, 12:28 PM
try this: Loading External Data (http://www.howtocreate.co.uk/loadingExternalData.html)

cowkiller6
07-04-2005, 04:24 PM
I added the line: if (results!=='')

and now it works awsome in mozilla/firefox. But, in ie it gives the error, and when I updated the value to 10 it changed in firefox, but ie still showed the old number (20).

I also read the Loading External Data page, but I didn't find anything that jumped out at me as being the problem.

Thank you

jscheuer1
07-05-2005, 08:41 AM
It is showing 10 in IE now. It may have been cached or needed time to catch up somehow. I've seen this used but, have no real idea what it means. If it means what I think it might, it will clear up the IE error (your existing code is black, additions are red):


results=''
if (http.readyState == 4)
results = http.responseText;Worth a shot.

cowkiller6
07-05-2005, 05:31 PM
Thanks! That took care of the error, but now I think it is indeed storing it in a cache. I added these two lines (the bold ones) to try and stop it, but after I update the value, it shows the change immediatly in firefox but in ie I have to click tools-internet options-delete files-ok, and when I hit the last ok, and the site is up it updates the value.



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>ZIP Code to City and State using XmlHttpRequest</title>
<META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE">
<META HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE">
<script language="javascript" type="text/javascript">
var url = "getCityState.php"; // The server-side script
function handleHttpResponse(){
results=''
if (http.readyState == 4)
results = http.responseText;
if (results!=='')
document.getElementById('city').value = results;
}

jscheuer1
07-05-2005, 11:10 PM
Well, I noticed that you are displaying this page in a frameset, 'forwarding' to it from the frameset page. Often this can be the reason why in IE the page remains cached.

Try using all these meta tags on both frameset and display page in place of yours (some are duplicates):

<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="Mon, 01 Jan 1990 12:00:00 GMT">
<meta http-equiv="Cache-control" content="no-cache">
<meta http-equiv="Cache-control" content="must-revalidate">
<meta http-equiv="Cache-control" content="max-age=0">

If that doesn't work, I'd try having it displayed on its own, rather than in the frameset.

It may be your IE browser's cache settings. Under temporary internet files (the same place you go to delete the files) click the settings button. If it is set to never, that is the problem and an unusual setting. Mine is set to automatic and I've never observed this behavior you have reported for this page in IE.

cowkiller6
07-06-2005, 02:15 AM
I added all those lines, and it still caches it.

I took a guess that those fancy boxes the nubmer was displayed in was a frameset. I took some stuff out and it worked.

I now have it being displayed in an input box, however as a final question. Is there a way just to display this number whereever I want in the document. Currently I do this to display it:


document.getElementById('city').value = results; //the results from the php query are given the id of city

//later on...

<input type="text" name="city" id="city" /> // a text box shows the value named city

But is there a way to give this a php variable, or I am not good at javascript but I assume they have variables?

THANK YOU

jscheuer1
07-06-2005, 06:12 AM
Well, the PHP people sent you here, I don't do PHP much. I'm mostly just an HTML and javascript guy. Anyways, the frameset I was talking about is the page that you gave for the link to this script. It is a page that sets up frames hence, a frameset. I'm glad you figured it out though and apparently that wasn't the problem. Oddly, I've never seen it do what you have, not update. On to your other question:

Is there a way just to display this number whereever I want in the document.Yes, that is what I was trying to explain before with post 328610 (http://codingforums.com/showthread.php?p=328610) from this thread. Using the method in that post, where you now have:

document.getElementById('city').value = results;You can use:

document.getElementById('city').innerHTML = results;Once you make that change, the receiving element can be any element that displays text, anywhere in the document. A span is probably the most useful as, it can go right into a sentence. Ex:

<p>The city value is <span id="city"></span>, for the current time and session.</p>Where you put that span in your document is up to you (I just put it in a paragraph as an example), it will display the value in the variable 'results' as ordinary text.

cowkiller6
07-06-2005, 06:21 AM
Thank you very much. I believe this is all sorted out :thumbsup: .


THANK YOU



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum