0

Possible Duplicate:
pass php variable value to javascript

I have a piece of php code

function formLetterTabPage($redirect_url, $letter){
  $test = 123;
  foreach (range('A','Z') as $val) {
    if($val == $letter){
        echo '<li class="a" id="li_'.$letter.'" onclick="tab_click('.$letter.')">'.$letter.'</li>';
    }else{
        echo '<li class="b" id="li_'.$val.'" onclick="tab_click('.$letter.')">'.$val.'</li>';
    }
  }
}

and my javascript function tab_click is quite simple:

function tab_click(f){
  alert(f);
}

the key part is here:

echo '<li class="a" onclick="tab_click('.$letter.')">'.$letter.'</li>';

it cannot work out ! so I change it like this:

$test = 123;
echo '<li class="a" onclick="tab_click('.$test .')">'.$letter.'</li>';

it works perfert, and the page show me 123! I wonder why this happen? And I checked the html code, it ok:

<li class="navi_letter_leftb" id="li_A" onclick="tab_click(A)">A</li>

ok, I don't know why?

Community
  • 1
  • 1
diligent
  • 2,282
  • 8
  • 49
  • 64
  • Because in your first sample you end up with `onclick="tab_click(A)"`. Not valid. Use manual quotes in the right content, or json_encode() or htmlspecialchars() for escaping. – mario Oct 10 '12 at 15:13

2 Answers2

4

You need additional quotes in your javascript for string parameters:

echo '<li class="a" onclick="tab_click(\''.$letter.'\')">'.$letter.'</li>';

In your test case $test = 123; you are passing an integer, so the quotes are not needed.

EDIT

Output without quotes (invalid javascript):

<li class="a" onclick="tab_click(a)">a</li>

Output with quotes:

<li class="a" onclick="tab_click('a')">a</li>
Tchoupi
  • 14,560
  • 5
  • 37
  • 71
1

If you pass $test = 123 your javascript it's working because you're passing an integer value.

But your $letter it's a string and so the resulting html code it's wrong:

<li class="navi_letter_leftb" id="li_A" onclick="tab_click(A)">A</li>

You have to wrap your string between quotes ''. So it should be:

<li class="navi_letter_leftb" id="li_A" onclick="tab_click('A')">A</li>

and you should change your code to:

echo '<li class="a" onclick="tab_click(\''.$letter.'\')">'.$letter.'</li>';
Cirou
  • 1,420
  • 12
  • 18