简体   繁体   中英

Passing PHP variables as strings to javascript

Somehow my php function, which creates a button, which calls a javascript function, does not pass the php variables as strings.

function addTableEntry($id, $name)
{
    echo('<tr>
              <td>'.$id.'</td>
              <td>'.$name.'</td>
              <td><a href="#groups" onClick="activateGroupSettingsOverlay('.$id.','.$name.')">Manage group</a>
              </tr>');
}

addTableEntry(1,"livingroom");

The function activateGroupSettingsOverlay() always gets called with (1, livingroom) whenever it is clicked and i get an error "livingroom is undefined".

How can i pass $name as a String? I tried to put quotes around it (like this: '.$id.',"'.$name.'" , but that did not work.

You have to "escape" quotes inside a string if you want them to persist:

echo '..... onClick="activateGroupSettingsOverlay('.$id.',\''.$name.'\')"....'

The important thing are the backslashes before the (single) quotes.

The reason it wasn't working is because you were not including quotes in the javascript.

While other answers "fix" the issue they don't really explain it, to be clear this line

  <td><a href="#groups" onClick="activateGroupSettingsOverlay('.$id.','.$name.')">Manage group</a>

Is output like this

  <td><a href="#groups" onClick="activateGroupSettingsOverlay(1,livingroom)">Manage group</a>

As is, the livingroom does not have quotes and so javascirpt is treating it as a variable, hence the undefined error. To fix it you want it to look like this when output.

  <td><a href="#groups" onClick="activateGroupSettingsOverlay(1,'livingroom')">Manage group</a>

Modifying this line is all you have to change

  <td><a href="#groups" onClick="activateGroupSettingsOverlay('.$id.',\''.$name.'\')">Manage group</a>

Adding the single quotes \\' with escaping.

Personally for things like this I like to use what is called a HEREDOC or NEWDOC <<<HTML HTML; and <<<'HTML' HTML; respective. HEREDOC is like using a " and new doc is like using ' in that you cannot use php variables within a NEWDOC but you can within the HEREDOC if you enclose them in { } braces. Because of this we'll want to use a HEREDOC so we can use php variables in the output.

function addTableEntry($id, $name)
{
    echo <<<HTML 
        <tr>
            <td>'.$id.'</td>
            <td>'.$name.'</td>
            <td><a href="#groups" onClick="activateGroupSettingsOverlay({$id},'{$name}')">Manage group</a>
        </tr>
HTML;
}

addTableEntry(1,"livingroom");

http://php.net/manual/en/language.types.string.php - scroll down to where it says HEREDOC

The advantage to doing this is that you don't have to escape the single quotes, which makes it way more readable IMO. The trick with HEREDOC, or NEWDOC, is the ending HTML; has to start a new line and can be the only thing on that line, no leading or trailing spaces, or it won't work properly..

For this case it is probably simple enough to get away with how you are doing it, but if you needed to use concatenation in javascript, the quotes would become a hassle. For example say you wanted to add a html image tag using javascript with a javascirpt variable for the image name, but use php to get the server host name( html and variables in javascript ).

 echo '
      var foo = "image.jpb";
      $(body).html( \'<img src="'.$_SERVER['HTTP_HOST'].'\'+foo+\'" />\' );
 ';

This quickly becomes unmanageable because ( not even sure if I have that right, anyway ). Compare how much cleaner this is, because you are not wasting the quotes in php....

echo <<<HTML
     var foo = "image.jpb";
          $(body).html( '<img src="{$_SERVER['HTTP_HOST']}'+foo+'" />' );
HTML;
Please try with this code:-

function addTableEntry($id, $name)
{
    echo("<tr>
              <td>".$id."</td>
              <td>".$name."</td>
              <td><a href=\"#groups\" onClick=\"activateGroupSettingsOverlay($id,'$name')\">Manage group</a>
              </tr>");
}

addTableEntry(1,"livingroom");

Change

onClick="activateGroupSettingsOverlay('.$id.','.$name.')"

to

onClick="activateGroupSettingsOverlay('.$id.',"'.$name.'")"

@chandresh_cool是对的,你必须“强制”引号

onClick="activateGroupSettingsOverlay('.$id.',\''.$name.'\')"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM