adding php to button onclick

Discussion in 'Web Design and Development' started by mbpowner, Nov 5, 2016.

  1. mbpowner macrumors regular

    Aug 19, 2016
    How do I add php to button onclick? I dont wish to use jquery as i have been using javascript and i dont wanna complicate things and jqeury is all i could generally find.

    does it basically work the same way as in javascript, you make a function using php then call the function using inclick ?

    e.g. <?php function Myfunction()

    <input type = "button" name="click here" onClick="return Myfunction()";>

    sorry for my n00b question haha
  2. mikes63737 macrumors 65816

    Jul 26, 2005
    PHP code runs on the server, while Javascript runs on the client side. So you would need to send a request to the server, whether asynchronously (eg, AJAX) or synchronously (using a link or form submission), in order to execute PHP code in response to a click.

    What you CAN do is use PHP to help generate the page, like this:

    onclick="return <?php echo $functionName; ?>();"

    If $functionName = "sayHello" (for example), then clicking that will call sayHello() in the Javascript.

    A more realistic example could be something like...
    onclick="return addToCart(<?php echo $item->Id; ?>);"

    Where addToCart() is Javascript code.
  3. mbpowner thread starter macrumors regular

    Aug 19, 2016
    Thank you!

Share This Page