2

I am trying to call a function in another .php file from this one by clicking a button, and I encountered this method elsewhere on the Internet, but I'm not sure if it works. I reduced the PHP code to simply printing something onscreen twice instead of calling another file, to demonstrate what is going wrong:

<?php
echo "hello";
?>
<?php
echo <<<END
<html>
<body>
<button type="button" onclick="handleButton()" id="button1">PHP Test</button>
<script type="text/javascript">
function handleButton()
{
   document.getElementById("button1").innerHTML = "PHP Test<?php echo 'HELLO';?>";
}
</script>
</body>
</html>
END;
?>

Shouldn't pressing the button print "HELLO" on screen? Instead the HTML source for the button becomes:

<button type="button" onclick="handleButton()"
id="button1">
PHP Test
<!--?php echo HELLO;?-->
</button>

And nothing happens when the button is clicked. Since "hello" prints fine, why is the server commenting out the second php echo command?

P.S.: I anticipate a lot of comments saying, "Why are you trying to do this in the first place?" I know I can make an HTML form that submits to a php file, but my goal here is to make multiple buttons onscreen, each leading to a different php file. I know that I could also make a form lead to a single php file that looks at which button on this screen was pressed, and calls the appropriate php file, but I'd like to avoid making another php file just to do that, if this can work. So unless I'm missing a more efficient approach, I'd prefer that we just stick to the subject of why the server is commenting out that PHP code. Thanks.

user1134918
  • 129
  • 1
  • 8
  • do you mean – redmoon7777 Jan 06 '12 at 19:31
  • 2
    Not really :-) The single-quotes don't help. The button just gets "" added to it. – user1134918 Jan 06 '12 at 19:32
  • There are just so many wrong things in the snippet you've posted above that I'm not entirely sure what it is that you're trying to achieve. Lets start by you quoting the strings properly. Are you sure you understand how HTML/JS and PHP work in terms of what runs on the client side (browser) and what runs on the server side (PHP)? Doesn't seem to me that you do. – Lior Cohen Jan 06 '12 at 19:33
  • @Lior: I like to think that I do. My intention is to "hide" the PHP until JS adds it to the button post-click. I can also break up the PHP code string into its components to fool the parser ("<" + "?php echo hello;"), but this has the same result, a string of commented-out PHP. – user1134918 Jan 06 '12 at 19:35
  • 2
    Not sure why people downvoted this question. It's a valid question, even if not the most useful. Some beginners would possibly learn something from this question someday. My 2c. – Lior Cohen Jan 06 '12 at 20:05

5 Answers5

3

PHP is a server side language and is executed before the user gets the data. This means you cannot call a PHP function from JavaScript. To do that, you have to make an AJAX request to a PHP page, and return the results there. Also, be sure to put Hello in quotes. I'd recommend looking up some tutorials on PHP and JavaScript so you can get the hang of the interactions between the two, and how to make them do what you want them to do.

LoveAndCoding
  • 7,857
  • 2
  • 31
  • 55
  • Are you super-duper sure? If the PHP is getting executed before the JavaScript can execute, why don't I see "helloHELLO" onscreen? Instead I see the PHP in the page source, commented out. – user1134918 Jan 06 '12 at 19:33
  • 2
    bevause you have your php inside php string - it will never execute – SergeS Jan 06 '12 at 19:34
  • 1
    @SergeS is correct. You have your PHP in an echo, which means it will get outputted as is, without executing the code – LoveAndCoding Jan 06 '12 at 19:35
  • Oh, wow, I can't nest the php tags? Well, that's a roadblock. – user1134918 Jan 06 '12 at 19:41
  • No, nesting PHP is not allowed. PHP is a *server* language, and is never sent to the client. I'd recommend reading through the tutorials I liked to in my answer to find out more how to run server-side code from the client (an AJAX request). – LoveAndCoding Jan 06 '12 at 19:43
  • I knew I would get a lot of responses reminding me that PHP is server-side. This approach was supposed to sneak around that by embedding the PHP in JS (so it gets sent downstream to the browser). Apparently the no-nesting rule is what breaks the method, but that has nothing to do with where the language is being parsed, just a limitation of the parser itself. – user1134918 Jan 06 '12 at 19:54
  • @user1134918 The browser does not know how to parse PHP. It is a server side language, and is interpreted by the PHP installation on the server. An end user cannot parse PHP, it can *only* be run on the server side of things. It's not a 'rule', it's the way things function fundamentally. – LoveAndCoding Jan 06 '12 at 19:59
  • The browser is not intended to parse the PHP in my code, just to "hold onto it" until the button is clicked. As I feared, everyone assumes I am ignorant instead of realizing that the PHP code in the JS code is actually being sent downstream to the browser. Try it if you don't believe me, or see my convo below with Lior where I pasted in the source from my browser. – user1134918 Jan 06 '12 at 20:04
  • @user1134918 The server sends your page downstream and then *stops sending information*. This means you cannot send code back to the server to be run. You have to make another call to the server page (using AJAX) to run code. Connections between server and client are not maintained while you are on the site, pages are sent on demand and that is it. (New technologies will change that a bit, but not in the methods you're talking about). I know the php is being sent down to the server, but once it's there, it is text and no longer code. – LoveAndCoding Jan 06 '12 at 20:09
  • Okay! So what you're saying is, appending the PHP to the button's HTML code does not result in the PHP being parsed and run. I was thinking that the code would be re-appraised by the PHP parser at that point... rats. – user1134918 Jan 06 '12 at 20:18
  • No, once it is handed off to the user, it is considered text. – LoveAndCoding Jan 06 '12 at 20:19
  • My hope was that the server would re-evaluate the new PHP on the page, but I guess that doesn't make sense after all, because as you said, the server runs the PHP first and then everything is left to the browser. I guess I assumed that the server was disallowing my inserted PHP by commenting it out, when it was actually the browser that was doing that. Sorry to waste your time then, and thanks. – user1134918 Jan 06 '12 at 20:28
0

A side note, strings need to be in quotes.

<?php echo "hello"; ?>
ok1ha
  • 637
  • 1
  • 11
  • 30
  • Yes, please, it burns us. Quotes, please. – Lior Cohen Jan 06 '12 at 19:34
  • I know that's probably more correct, but I was trying to avoid extra variables entering into the equation. Using double-quotes on the string in the JS command requires escaping them, and I wanted to eliminate that as a possible issue in the execution of the PHP. Besides which, "echo hello;" works just as well as "echo "hello";". – user1134918 Jan 06 '12 at 19:37
  • 1
    It's not "more correct". It's just correct. The PHP language syntax isn't a matter of opinion, mind you ;-) – Lior Cohen Jan 06 '12 at 20:07
0

If I understand what you're trying to do here, try the following:

<html>
  <body>
    <button type="button" onclick="handleButton()" id="button1">PHP Test</button>
    <script type="text/javascript">
      function handleButton()
      {
        document.getElementById("button1").innerHTML = "PHP Test <?php echo 'HELLO';?>";
      }
    </script>
  </body>
</html>

Suppose the code above is in a file "index.php" and you're requesting this file using http://example.com/index.php. This would result in the following HTML being sent to your browser (which you can see if you do "view source" on the page loaded into your browser):

<html>
  <body>
    <button type="button" onclick="handleButton()" id="button1">PHP Test</button>
    <script type="text/javascript">
      function handleButton()
      {
        document.getElementById("button1").innerHTML = "PHP Test HELLO";
      }
    </script>
  </body>
</html>

Clicking on the button has nothing to do with PHP at that point, since PHP has already completed its role in loading the page. At this point, if you wish to make a request to a server side PHP script, you MUST use either a form, an AJAX request or an IFRAME (and I could go on here).

I hope this clears it up a bit, but I must emphasize the fact that you should do some more reading before attempting to do what you're trying to do here.

Good luck!

Lior Cohen
  • 8,985
  • 2
  • 29
  • 27
  • I do understand what I'm trying to do, I'm just being unconventional about it :-) I will probably just use the method I mentioned in my P.S. in the question. Fwiw, I did try your approach too. It seems like it should work, but it changes the button name to "PHP Test?>" and the source shows two commented-out lines now instead of one: and . – user1134918 Jan 06 '12 at 19:49
  • Just read your addendum edit. In fact, the browser receives this as source:`hello ` – user1134918 Jan 06 '12 at 19:58
  • Sorry if that formatting is not the best, I'm new here. Anyway, as you can see, the PHP code actually remains intact instead of being run by the server. It then gets appended to the page source when the button is clicked. AFAIK, the only reason my original code above doesn't work is the no-nesting issue with php tags. – user1134918 Jan 06 '12 at 20:00
  • 'I am trying to call a function in another .php file from this one by clicking a button, and I encountered this method elsewhere on the Internet, but I'm not sure if it works.' <-- this suggests to me that you don't. Sorry, not trying to be sarcastic or condescending here. If you really want to do this properly, first understand how things work. Copy/Pasting obscure code snippets from a website and trying to patch them into something that works is usually not the way to go. – Lior Cohen Jan 06 '12 at 20:00
  • Re: your 2nd comment, this is because heredoc/nowdoc doesn't allow you to insert PHP code the way you are. First of all, you're already inside a , which will not get you what you want. Take a look at the modified code snippet in my answer to see how this should be done. – Lior Cohen Jan 06 '12 at 20:03
  • Take a look at this: http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc – Lior Cohen Jan 06 '12 at 20:06
  • I now understand that PHP does not like to encounter a second opening tag when it's already parsing a block of PHP. I did try your code, and described in my first response above what the results were. But at least we are in agreement now as to why my code does not work. – user1134918 Jan 06 '12 at 20:08
  • Okay, just to wrap this up, it was not the nesting of php tags in particular that was the issue, it's that the server will not re-evaluate the page after I tell the browser to insert more PHP code into it. In hindsight, I should have seen this on my own. I promise to write "PHP is server-side and doesn't care what happens in my browser after it sends it the HTML" 100 times on the blackboard after school. – user1134918 Jan 06 '12 at 20:36
  • I'm glad you figured it out. Do some reading buddy. Good luck! – Lior Cohen Jan 06 '12 at 20:39
-1

Beacuse of HTML have no sense about where it comes from ( php ) - if this value is static - put it there and don't disturb with executing it from cleint side otherwise use AJAX in any form - to learn it look google

PS At first take bit ore learning on how does web works - it will slove this and other similiar problem before you get them

SergeS
  • 11,533
  • 3
  • 29
  • 35
  • Thanks, I've heard of AJAX but didn't want to get involved with a new language/framework for something so simple. I'll probably just have all the buttons report to a central PHP file before I do that. – user1134918 Jan 06 '12 at 19:43
-1

You'd be better off using a variable declared earlier... (this is tested and works)

<?php
   $buttonTitle = "HELLO";
   echo 'hello';
?>

<?php
echo <<<END
<html>
<body>
<button type="button" onclick="handleButton()" id="button1">PHP Test</button>
<script type="text/javascript">
function handleButton()
{
  document.getElementById("button1").innerHTML = "$buttonTitle";
}
</script>
</body>
</html>
END;
?>
Web User
  • 7,438
  • 14
  • 64
  • 92
  • Thanks Web User, but unfortunately I need to run actual PHP code when the button is clicked. Unless PHP has the ability to store function calls in variables and execute them from by evaluating the variables, I guess this method isn't going to work out for me. – user1134918 Jan 06 '12 at 20:26
  • You could try this... $var = 'hello'; function hello() { return 'hello world'; }; echo $var(); Use XMLHttpRequest to make an asynchronous invocation of your PHP function. That is essentially [Ajax](http://www.w3schools.com/ajax/ajax_example.asp). If it makes sense, check out popular JS frameworks which all have friendly wrappers for Ajax functionality. – Web User Jan 07 '12 at 21:59