0

I got really confused when i tried to transfer variables from php to js. everything is fine when i try to get value using an id
for example:

var name = $("#name").val();

but my question is, if i want to convert for example this variable:

$id = 182938; //the id of the user

to this variable:

var id;

this question might be dumb... maybe easy for you, but not for me :p
I have looked it up and only found something like this anywhere i looked for:

<?php
$number = rand();
?>

<script language="javascript">
var num = <?php echo $number ?>
</script>

Does it have the same affect as passing down the value?

Thanks!!

Baruch
  • 1,618
  • 5
  • 23
  • 42
  • The sample above is correct. I'm not sure I understand your question. – Paul Dessert Apr 24 '12 at 00:42
  • @Paul Im sorry for not being clear, sometimes i get my variable as undefined. my question is, is the way that i wrote right? or is there another, better way to do it? I am new to everything in js and it confused me... – Baruch Apr 24 '12 at 00:45
  • If you do a view source on the page or something like alert(num), you will see the value of num. – jimiyash Apr 24 '12 at 00:45

3 Answers3

1

Not quite. Encoding as JSON will ensure that it is a valid JavaScript literal.

var num = <?php echo json_encode($number) ?>
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • @Jasper: Because it may not always be a number. – Ignacio Vazquez-Abrams Apr 24 '12 at 00:44
  • 2
    @Jasper you may have a string instead of a number which would cause a JS error with Joseph's method. I think json encode is a bit overkill though and if I know it's a string, I usually just `var str = ""`, which works as long as you don't have any double quotes. Don't forget your terminating ';' @ Ignacio ;-) – Authman Apatira Apr 24 '12 at 00:45
  • 1
    @Authman: The `;` is optional if you're closing the PHP script block. – Ignacio Vazquez-Abrams Apr 24 '12 at 00:48
  • @AuthmanApatira, but that by itself is no reason to drag json into this. There are other functions in PHP that can guarantee the output is a number. I just don't see a good reason to (ab)use json for this, but I am open for good arguments – Jasper Apr 24 '12 at 00:49
  • when i try to put these lines in my code var num = ; alert(num); the JS won't work at all. – Baruch Apr 24 '12 at 00:51
  • Agreed; my pref is to just encapsulate in double quotes, and if it's a user defined string, then I'll additionally escape \" internal quotes. – Authman Apatira Apr 24 '12 at 00:51
  • @Baruch when looking at the generated HTML, what is the part corresponding to those php lines? – Jasper Apr 24 '12 at 01:01
  • What do you mean? i echo everything (every part of the html code) from the same php file that has the js connected to. the js is located in the js folder and connected to index.php (the file im working on) – Baruch Apr 24 '12 at 01:05
  • @Baruch I meant that I want you to go view the page, open the source and copy the part that was produced by `var num = ; alert(num);`and report back here with the result – Jasper Apr 24 '12 at 01:07
  • nvm... it was a syntax error... i forgot putting a '});' at the end of the action (click action), Thanks everyone! – Baruch Apr 24 '12 at 01:12
0

what the code does is:

<?php
    $number = rand();  //assign random number to $number. let's say it's "3"
?>

//then these are printed on the page normally
<script language="javascript">
    var num = <?php echo $number ?> //the $number is echoed at this position
</script>

and then the browser receives:

<script language="javascript">
    var num = 3;
</script>
Joseph
  • 117,725
  • 30
  • 181
  • 234
-1

You have to generate syntactically VALID javascript. PHP can echo text into ANY part of the page it's generating, but that doesn't necessarily mean it's actually USABLE text. In your case, you've forgotten a ;, so your generated javascript is actually a syntax error:

var num = <?php echo $number ?>;
                               ^--- missing

The same sort of thing occurs when you're outputting text. Consider where you're storing someone's name into a variable:

<?php
   $name = "Miles O'Brien"; // <-- note the single quote
?>
<script>
   var name = <? php echo $name ?>;
</script>

This LOOKS ok, but it'll actually generate yet another syntax error:

    var name = Miles O'Brien;

there's no quotes around the whole string, and the embedded quote will START a string in javascript, leading the JS interpreter to complain about an undefined variable "Miles", an undfined variable "O", and an unterminated string literal.

Instead, the PHP should have been:

 var name = <? echo json_encode($name) ?>;

The JSON encapsulation guarantees that you're embedding syntactically valid Javascript values.

Marc B
  • 356,200
  • 43
  • 426
  • 500
  • While I do not advocate (or even condone) leaving them out, semicolons *are* optional, so it's not the problem you are suggesting it is. – Jasper Apr 24 '12 at 00:53