1

I am trying to pass more then 1 php variable in parameter in a onclick.

<button type="button" class="btn btn-dark bmd-btn-fab bmd-btn-fab-sm" 
onclick="<?php echo 'analyse(\'' . $name . '\', \''. $type .'\')'; ?>">
    <img src="../assets/add.png" />
</button>

For only 1 parameter it worked with this :

onclick=<?php echo "analyse('$name')"; ?>"

and this:

onclick="<?php echo 'analyse(\'' . $name . '\')'; ?>"

6
  • 2
    echo "analyse('$name', '$type')"? Commented Feb 4, 2020 at 20:09
  • no sorry it's more difficult then that the ',' is the issue Commented Feb 4, 2020 at 20:12
  • And what is the issue? Commented Feb 4, 2020 at 20:13
  • ^^ Explanation of @u_mulder's comment-- single quotes only allow literals, no strings within the quotations. Double quotes will allow you to mix literals with strings -- as well as escaped predefined strings such as \n newlines etc etc Commented Feb 4, 2020 at 20:14
  • I can't tell if analyse is a JS or PHP function... in order for it to work on button click, it would need to be a JS function....... Commented Feb 4, 2020 at 20:16

1 Answer 1

1

I would put this as a comment but the placeholder text in comments says to not put answers in comments...

First, analyse has to be a JS function, not a PHP function.. Also, you don't need to put analyse inside of the <?php code block..

<button onclick="analyse('<?php echo $name ?>', '<?php echo $type ?>')">

Full demo PHP file:

<?php
$name = "John Smith";
$type = "Best Type"
?>
<div>
    <button onclick="analyze('<?php echo $name ?>', '<?php echo $type ?>')">Show Name</button>
    <p id="results"></p>
</div>
<script>
    function analyze(name, type) {
        document.getElementById("results").innerHTML = "<b>NAME:</b> " + name + " <b>TYPE:</b> " + type;
    }
</script>

To elaborate, just in case you wanted to use a PHP function to return a name or type, you would use it like so:

<?php
$name = "John Smith";
$type = "Best Type";

function get_Name($nameToGet) {
    return $nameToGet;
}

function get_Type($typeToGet) {
    return $typeToGet;
}
?>
<div>
    <button onclick="analyze('<?php echo get_Name($name) ?>', '<?php echo get_Type($type) ?>')">Show Name</button>
    <p id="results"></p>
</div>
<script>
    function analyze(name, type) {
        document.getElementById("results").innerHTML = "<b>NAME:</b> " + name + " <b>TYPE:</b> " + type;
    }
</script>
Sign up to request clarification or add additional context in comments.

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.