2

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.

LethalPapercut
  • 163
  • 1
  • 1
  • 6

1 Answers1

10

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..

raidenace
  • 12,789
  • 1
  • 32
  • 35
  • 3
    Haha. Love the analogy...+1 – War10ck May 03 '13 at 20:39
  • Cleared up the theory for me really well but how would I go about implementing AJAX to do what I need in this instance? – LethalPapercut May 03 '13 at 20:44
  • Well you could start by checking how to make an ajax call using [jquery](http://api.jquery.com/jQuery.ajax/) which is pretty easy to understand.. There are some really easy tutorials out there.. – raidenace May 03 '13 at 20:46