0

The JS function is

function func(arg){  
    alert(arg);  
}

When I do

echo "<div onclick=\"func($arg)\">Text</div>";

in php, it doesnt work but when I do

echo "<div onclick=\"func()\">Text</div>";

it works and an alert with undefined text pops up.

How do I pass argument?

1
  • What are you trying to pass? In the onclick attribute you need to have valid Javascript. Is $arg a PHP variable? Commented Jul 2, 2013 at 15:51

3 Answers 3

1

You need to quote the arguments. e.g.

<?php
$foo = 'bar';
?>

echo "function($foo) { ... }";

is going to produce the code

function(bar) { ... }

where bar will be interpreted as an undefined variable.

Safest method is to output your PHP variables via json_encode(), to guarantee you're producing syntactically valid javascript. e.g.

echo 'function(' . json_encode($foo) . ') { ... }';

which would produce (in this case)

function ('bar') { ... }
Sign up to request clarification or add additional context in comments.

1 Comment

Beat me to it, with a more thorough answer. +1.
0

You need to wrap $arg in quotes. Example:

echo "<div onclick=\"func('$arg')\">Text</div>";

(using single quotes around arg as you're using double quotes for the string)

Comments

0

You can do like this (if $args exists of course)

echo '<div onclick="func('.$arg.')">Text</div>';

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.