0

This IS a duplicate from Calling a php function by onclick event, but I have a question on it. The answer I had a question on is by timpanix, and basically it won't work.

He said to execute some PHP code in a On Click event do this:

onclick="document.write('<?php //call a PHP function here ?>');"

and call the PHP function. Yet whenever I try it:

<button id="profileinformationbutton" input type="submit" value="Login" onclick="document.write('<?php profileupdated() ?>');"> Update Profile </button>

it prints out ');" > Update Profile, yet I have no clue why. It is inside of a form, and the PHP function looks like this:

<?php
    function profileupdated() {
?>
        <div id="profileupdated"> Profile Updated </div>
<?php
    }
?>

Why would the code be displaying this? Please help! :) Thank You.

EDIT

The code does not seem to be writing Profile Updated to the page, any idea why?

Community
  • 1
  • 1
michael jones
  • 710
  • 1
  • 8
  • 17
  • 2
    possible duplicate of [What is the difference between client-side and server-side programming?](http://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming) – Dan Smith Feb 09 '15 at 17:32
  • 2
    escape the double quotes inside your php function to fix your problem – Lorenzo Marcon Feb 09 '15 at 17:34
  • You're echo div with double quote attribute inside double quote attribute. The php code will not execute on the client but on the server before html is rendered. – jcubic Feb 09 '15 at 17:34

3 Answers3

1
    function profileupdated() {

        echo "<div id='profileupdated'> Profile Updated </div>";

    }

Also if you only want to print this value to your tag why you're using function? Assign it to a variable.

like

$myVar = '<div id="profileupdated"> Profile Updated </div>';

Then use this variable where you want?

you should echo or return your function body. Carefull! I changed quotes!

hakki
  • 6,181
  • 6
  • 62
  • 106
0

Your PHP function is writing to the page already, rendering the document.write (javascript) useless. Try this:

<?php 
    function profileupdated() {
        return "<div id='profileupdated'>Profile updated</div>";
    } 
?>

I do want to note though that you might want to consider a cleaner way of doing this: If you just want to display a fixed text ("Profile updated"), stick to pure client-side Javascript.

Otherwise (if there's logic to be done server-side), you might want to decouple server and client and use an AJAX call and JSON to transfer your data.

Grüse
  • 1,096
  • 2
  • 11
  • 24
-1

PHP is a server side programming language, you are executing the JavaScript on the client side. If you want to call a PHP script from your JavaScript you need Ajax, f.e. jQuery.

Thomas
  • 11,272
  • 2
  • 24
  • 40