1

I have 2 pages, one PHP and one Javascript. I'd like to pass the variable from this PHP script on one page:

$strFind="SELECT * FROM  cometchat_chatrooms_users WHERE userid=$curmemid";
$result=mysql_query($strFind) or die(mysql_error());
$row=mysql_fetch_array($result);
$room=$row['chatroomid'];

to this Javascript on another page:

var timestamp = 0;
var currentroom = $room;
var heartbeatTimer;
var minHeartbeat = 3000;
var maxHeartbeat = 12000;

How can I do this?

Gumbo
  • 643,351
  • 109
  • 780
  • 844
John Sims
  • 227
  • 3
  • 14
  • thanks for all the answers but none of this is working, I thought for sure the sessions one would work. – John Sims Jul 22 '10 at 06:53
  • Or you can use an AJAX request or a hidden input. When you are using PHP sessions remember, that your JavaScript must be generated by PHP too. – CSchulz Jul 22 '10 at 07:21

7 Answers7

8

You can do this, when the JavaScript is generated by PHP. Example given:

<?php
...
$curmemid = intval($externalValue);
$strFind = 'SELECT * FROM cometchat_chatrooms_users WHERE userid='.$curmemid;
$result = mysql_query($strFind) or die(mysql_error());

if (isset($result)) {
    $row = mysql_fetch_array($result);
    $room = $row['chatroomid'];
} else
{
    echo 'There is something wrong!';
    $room = -1;
}
...
?>
<script type="text/javascript">
var timestamp = 0;
var currentroom = <?php echo $room; ?>;
var heartbeatTimer;
var minHeartbeat = 3000;
var maxHeartbeat = 12000;
</script>
CSchulz
  • 10,882
  • 11
  • 60
  • 114
  • That will just try to assign the value of the *JavaScript* variable `$room` (which is undefined) to `currentroom`. – Quentin Jul 22 '10 at 06:37
  • No, that will assign the JavaScript variable `currentroom` with the value of the PHP variable `$room`. – CSchulz Jul 22 '10 at 06:40
  • 2
    @David Dorward: No, it wouldn't, this code is absolutely correct, `$room` is between `` – nico Jul 22 '10 at 06:41
  • 1
    @nico — it has been edited since I made the comment. Previously it was just: `var currentroom = $room`. – Quentin Jul 22 '10 at 06:43
  • 2
    This will break if $room is not a Number or stored in the database in a JS literal format (e.g. including the `"`s in a string or the `{` and `}` in an object). – Quentin Jul 22 '10 at 06:43
  • @David: That is correct. I found the mistake and corrected it immediately. – CSchulz Jul 22 '10 at 06:44
  • @David Dorward: Ah OK, sorry, I did not see it had been edited :) – nico Jul 22 '10 at 06:48
  • @nico — For some reason SO fails to keep a history if you make edits very soon after creating an answer. It is rather annoying. – Quentin Jul 22 '10 at 06:50
  • Didn't OP say the JavaScript lives on a separate page from the PHP script? Or is the answer also suggesting to keep both on the same page? – BoltClock Jul 22 '10 at 07:01
  • can't keep both scripts on the same page, the chat room js file has too many dependencies to move around. – John Sims Jul 22 '10 at 07:15
  • Then you can use PHP Sessions, an input hidden or an AJAX Request to get the data. – CSchulz Jul 22 '10 at 07:18
  • 1
    Well, you can get the contents of js with file_get_contents(), parse it with PHP (you could have some placeholder in the original js like ROOM_PLACEHOLDER and str_replace() it). No problem. – Richard Knop Jul 22 '10 at 07:55
3
<?php

$strFind="SELECT * FROM  cometchat_chatrooms_users WHERE userid=$curmemid";
$result=mysql_query($strFind) or die(mysql_error());
$row=mysql_fetch_array($result);
$room=$row['chatroomid'];

?>
<script type="text/javascript">
var timestamp = 0;
var currentroom = <?php if(isset($room))echo $room; else echo ""; ?>;
var heartbeatTimer;
var minHeartbeat = 3000;
var maxHeartbeat = 12000;
</script>
Bhanu Krishnan
  • 3,726
  • 1
  • 20
  • 40
2

Another option is that of PHP outputting a hidden element with the variable in it and then JS reading it.

For instance

<?php
echo '<input type="hidden" id="myvar" value='.$val.' />';
?>

and then in JS

 var v = document.getElementById("myvar");
 // do something with v.value

Of course this is easily spoofable by the client, so take 2 cautions:

1) use this only if it is not a problem for any user to be able to see the value of the variable (e.g. by looking at the source)

2) if the JS does anything that can be possibly "dangerous" e.g. does an asynchronous call to a PHP page that does something in the DB with that value, be sure to have proper checks in the second PHP page (NOT in the JS) to ensure that the value had not been tampered with

nico
  • 50,859
  • 17
  • 87
  • 112
  • 1
    htmlspecialchars! htmlspecialchars! Whenever you put data that you don't know is safe into a document, use htmlspecialchars! We don't like XSS security holes! – Quentin Jul 22 '10 at 06:50
  • As for the two warnings … they apply to any data you end up asking the client to send back to you. There is nothing special about embedding it in the HTML. – Quentin Jul 22 '10 at 06:51
  • @David Dorward: sorry? Which part of the data are you assuming is not safe? As for the two warnings, my point is that the JS may be only doing something client-side, in which case data tampering problems are not an issue. If it's doing something server-side then you should do appropriate checks on the server, that's all. – nico Jul 22 '10 at 06:57
  • $val, we have no idea what it is. – Quentin Jul 22 '10 at 08:49
  • @David Dorward: exactly, that's why I didn't sanitise it. If `$val` is a number you can just cast it to `int`, if it is pulled from the DB you can be sure is fine because you sanitised the input before putting it into the DB etc etc. It is really dependent from the situation, my whole point here was to use a hidden input. – nico Jul 22 '10 at 14:48
2

You cannot actually "pass" a variable anywhere. But only a scalar value. Frankly, you can pass only text data.
So, in case of javascript you have 2 options:

  1. To generate whole js code from PHP along with all it's variables. Much like to how you generate HTML.

  2. To request some variable from JS running in a browser, using AJAX technique.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
1

for another page you can use $_SESSION

<script type="text/javascript">
var timestamp = 0;
var currentroom = <?php echo $_SESSION['room']; ?>;
var heartbeatTimer;
var minHeartbeat = 3000;
var maxHeartbeat = 12000;
</script>

For same file/script sequence- its very simple, no need of SESSION

   var currentroom = <?php echo $room; ?>;
Sadat
  • 3,493
  • 2
  • 30
  • 45
  • thanks for responding Sadat, the page this java script should go one is a .js page, ; is not working. – John Sims Jul 22 '10 at 06:44
  • This is a fairly terrible example. Sessions are relatively complicated beasts and can lead to things such as race conditions very easily. It might be slightly better if it bothered to mention that you have to create a session and store data in it before you can pull anything out of it! – Quentin Jul 22 '10 at 06:49
  • @Jhon, I know that well. According to your question, you need it in another page. Remember one thing, you cant execute php in JS file unless you permit it from core server configuration. – Sadat Jul 22 '10 at 07:01
0

try to use Session to store your room variable and use it with javascript by the echo instruction

tarek
  • 141
  • 1
  • 3
  • 7
-2

The code will work as is. When the output (html and javascript) is generated by your php it will already have done the substitution. So your value will be inserted there as a literal. If it is a string, you'll still have to quote it though.

var currentroom = '$room';

will become

var currentroom = 'myroom';

in output.

Joeri Hendrickx
  • 16,947
  • 4
  • 41
  • 53