How to Pass PHP String Variable To JS From an Onclick Event

13,762

You need to enclose the string in quotes when passing to the JS function, as well as in PHP:

$ratelink = 'text string...';
echo '<div><span id="anything" onclick="updatePos(\''.$ratelink.'\')">Save</div>';
Share:
13,762
user175328
Author by

user175328

Updated on July 28, 2022

Comments

  • user175328
    user175328 almost 2 years

    This might have a simple answer, however I cannot figure out the correct syntax. I have the following onclick event echoed on a php page:

    $ratelink = text string...
    echo '<div><span id="anything" onclick="updatePos('.$ratelink.')">Save</div>';
    

    On my JS page, I have the function:

    function updatePos(ratelink)
    {
      alert(ratelink); 
    }
    

    My problem is that when $ratelink is a number, the variable will pass with no problems. However, when $ratelink is a text string, like in the above example, nothing gets passed and the alert doesn't execute.

    I think the following ('.$ratelink.') needs to be in a different syntax to pass text, but I don't know the exact format.