Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

mbpowner

macrumors regular
Original poster
Aug 19, 2016
174
14
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
 
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.
 
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.
Thank you!
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.