Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using php to create a button that calls a php function [duplicate]

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.

like image 989
LethalPapercut Avatar asked Jun 23 '26 13:06

LethalPapercut


1 Answers

Some basic misunderstandings here. PHP and Javascript does not interact like that

Let me give a rather silly analogy:

  1. You go to the coffee shop and order some coffee.
  2. The shop keeper gives you the coffee. You take a sip and find you need more sugar
  3. 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:

  1. You go to the coffee shop and order some coffee.
  2. The shop keeper gives you the coffee. You take the coffee with you and walk home
  3. You take a sip and find you need more sugar
  4. 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..

like image 69
raidenace Avatar answered Jun 26 '26 03:06

raidenace



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!