3

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.

4 Answers 4

8

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>';
Sign up to request clarification or add additional context in comments.

Comments

1

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....

1 Comment

Tried many ways but this one worked for me.
0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.