PHP variables in JavaScript

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
GeoTrail
Forum Newbie
Posts: 3
Joined: Fri Jun 06, 2003 5:40 pm
Location: Bergen, Norway
Contact:

Post by GeoTrail »

I've got a question on using JS with PHP.
I've made a simple counter using PHP and MySQL.

Now I need to be able to use it with a html page using JavaScript. I have tried everything I can think of, but maybe someone could help me out with this.

Here is what the html page looks like:

Code: Select all

<!-- File: test.html -->
<html>
<head><title>Test counter</title></head>
<body>
<script src="index.php?page=count&id=1" language="JavaScript">
</script>
</body>
</html>
And here is what the PHP code looks like:

Code: Select all

echo "<script>
<!--
document.write("Hits: ".$hits."<br />");
//-->
</script>\n";
Does anyone know how I can get the hit value displayed on the HTML page using JavaScript?
jason
Site Admin
Posts: 1767
Joined: Thu Apr 18, 2002 3:14 pm
Location: Montreal, CA
Contact:

Post by jason »

Code: Select all

<?php
echo '<script>
<!--
javascript_variable = "',$hits,'"
//-->
</script>';
?>
That should do it.
GeoTrail
Forum Newbie
Posts: 3
Joined: Fri Jun 06, 2003 5:40 pm
Location: Bergen, Norway
Contact:

Post by GeoTrail »

Didn't work :cry:
Here's what I got so far. Did I change the JS var correctly? Remember I'm not very good with javascript :lol:

Code: Select all

<?php
		if (isset($id))
        {
	        $query=mysql_query("UPDATE counter SET hits=hits+1 WHERE id='$id'");

	        $tmp = mysql_query("SELECT hits FROM counter WHERE id='$id'");
	        $count = mysql_fetch_array($tmp);
	        $hits        = $count["hits"];
			if (isset($hits))
            {
	        	//echo "<p>Hits: $hits<br />id: $id</p>\n";
echo '<script>
<!--
hits = "',$hits,'";
document.write(''hits'');
//-->
</script>';

            } else {
				echo "<p>Invalid counter ID</p>\n";
            }
        } else {
			echo "<p>No counter ID was set!!</p>\n";
        }
?>
Sorry that the code looks messed up. I copied it from the full script. It looks better in the full file. I swear ;)
GeoTrail
Forum Newbie
Posts: 3
Joined: Fri Jun 06, 2003 5:40 pm
Location: Bergen, Norway
Contact:

Post by GeoTrail »

Never mind. I figured out what I did wrong :oops:

Code: Select all

<?php
// PHP Script
echo "document.write("Hits $hits");";
?>

Code: Select all

&lt;html&gt;
&lt;head&gt;&lt;title&gt;Test counter&lt;/title&gt;&lt;/head&gt;
&lt;body&gt;
&lt;script src="http://localhost/counter/index.php?page=count&amp;id=1" language="JavaScript"&gt;
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
I just removed the <!-- and //--> from the PHP script. I noticed that I don't need those when adding the script using the src command in javascript. Problem solved ;)
Post Reply