简体   繁体   中英

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

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.

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>';

try this echo '<div><span id="anything" onclick=updatePos("'.$ratelink.'")>Save</div>'; if there is space in the $ratelink variable then it should be quoted in string....

Your string needs to be wrapped in quotes... so you'll need to make it

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

and make sure that you escape the string as well if it might have any quotes in it

Neither of the answers are correct. At least not the best option. Consider using json_encode() to pass any data from PHP to JS. This ensures that data is correctly escaped.

var myObj = <?=json_encode(array('php' => 'array'))?>;

console.log(myObj);

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