1

How do I pass 2 PHP variables in a javascript function?

This one is working

 echo '<button onClick = "count('.$increment.')">'.$counter.' </button>';

but when i do this

  echo '<button onClick = "count('.$increment.','.$pass.')">'.$counter.' </button>';

it does not work, what is the problem?

By the way these are the variables:

    $increment=5;
    $pass="sdfgd";
Tjoene
  • 320
  • 9
  • 18
Andre malupet
  • 91
  • 3
  • 12

4 Answers4

3

Try this dude......

<button onClick = "count('<?php echo $increment ?>','<?php echo $pass ?>')"><?php echo $counter ?></button>
Venkata Krishna
  • 4,287
  • 6
  • 30
  • 53
2
echo '<button onClick = "count('.$increment.',\''.$pass.'\')">'.$counter.' </button>';
1

If $pass contains exactly "sdfgd" and with exactly I mean double quotes includes, this isn't a valid statement anymore, because your parser will find double quotes "too early" and them will close the onClick event attribute

After variable expansion:

echo '<button onClick = "count('5','"sdfgd"')">'.$counter.' </button>';
-------------------------------------^

Take a look to the arrow

Edit

However, if you use a tool like firebug (if you run firefox), you can debug your code easily

Community
  • 1
  • 1
DonCallisto
  • 29,419
  • 9
  • 72
  • 100
  • so does that mean that currently there is no way i can input a string? how do i input a string defined variable like $pass. – Andre malupet Feb 14 '13 at 11:35
  • @Andremalupet Take a look [here](http://stackoverflow.com/questions/97578/how-do-i-escape-a-string-inside-javascript-inside-an-onclick-handler) – DonCallisto Feb 14 '13 at 11:40
  • ill try this one..this is same from jsonencode right?uhmm..its weird that firebug is actually returning the variable value as undefined yet it has a variable and a value..sorry for asking..but what does that mean..thanks anyway men..you are a big help. – Andre malupet Feb 14 '13 at 11:57
0

The generated HTML code should look like this:

<button onClick = "count(5,sdfgd)">5 </button>

The variable sdfgd is most likely undefined, therefore undefined gets passed to your function.

If you want to pass a string you have to use quotes, so that the generated HTML looks like this:

<button onClick = "count(5,'sdfgd')">5 </button>
dave
  • 4,024
  • 2
  • 18
  • 34