Using php to create a button that calls a php function
html, javascript, php
Solution
Some basic misunderstandings here. PHP and Javascript does not interact like that
Let me give a rather silly analogy:
- You go to the coffee shop and order some coffee.
- The shop keeper gives you the coffee. You take a sip and find you need more sugar
- You tell the shopkeeper who adds the sugar to your coffee. Lets call this action `addSugar()`.
Everything is cool here. Now what happens in this second scenario:
- You go to the coffee shop and order some coffee.
- The shop keeper gives you the coffee. You take the coffee with you and walk home
- You take a sip and find you need more sugar
- You tell the shopkeeper to `addSugar()`...? erm...
Well the shopkeeper aint there. In the same way, when a page reaches your browser, it has left the coffee shop. There is no PHP/shopkeeper around anymore
Your request to `addSugar()` that you are trying on button click using Javascript will not work.
What you will need to do is use something called `AJAX` which is a way to quickly run to the coffeshop just for adding a little sugar.. Its a broader topic and you will need to read about it, but there are tons of resources out there..
Problem
Currently I have the following but it doesn't like me very much: 1. index.php: ``` <!DOCTYPE html> <html> <body> <div id = "bookList"> <?php include("list.php"); ?> </div> </body> </html> ``` 2. list.php: ``` <?php echo '<button id = "read">Read</button><br><br>'; echo "<script type=\"text/javascript\"> $(\"#read\").click(function() { alert(\"<?php display(); ?>\"); }); </script>"; function display() { echo "hello"; } ?> ``` As is hopefully obvious from the code I posted above, I am attempting to create a button using php which when clicked on will in turn call a php function. I have not been successful as of yet. Any advice will be appreciated but I'd like my code to stay as close to what I currently have as possible.