-2

I am trying to pass a php variable inside js function but I am getting the following error:

Uncaught SyntaxError: Invalid or unexpected token

Here's my code:

<?php 
$author ="James Wilson";

echo '<li  onClick= getAuthor("'.$author.'");>';

?>
12
  • Can you show the whole errormessage? Commented Jul 18, 2016 at 16:07
  • Possible duplicate of pass string parameter in an onclick function Commented Jul 18, 2016 at 16:07
  • Try this '<li onClick="getAuthor(\''.$author.'\');">' Commented Jul 18, 2016 at 16:08
  • This is not the duplicate of the link you posted @splash58.. please check carefully. Commented Jul 18, 2016 at 16:10
  • @IsmailRBOUH, I tried this.. I get same error Commented Jul 18, 2016 at 16:10

2 Answers 2

2

You know that you need to pass a string to onClick attribute. In plain html it should be:

<li onClick="getAuthor('someone')">    

Construct this with proper escape characters in php.

echo '<li  onClick= "getAuthor(\'' . $author . '\')";>';
Sign up to request clarification or add additional context in comments.

3 Comments

I tried the exct code you shared but instead of printing James Wilson, it prints $author
Works, thank you very much. Got to know where I went wrong
Please see my first snippet. That is how your echoed php value should look like. So, you needed to construct it with proper escape characters.
2
echo "<li onclick=\"getAuthor('$author')\">";

2 Comments

I tried this: Getting this error: Parse error: syntax error, unexpected '$author' (T_VARIABLE), expecting ',' or ';'
That should work. Another way would be echo '<li onclick="getAuthor(\'' . $author . '\')">';

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.