简体   繁体   中英

PHP Script in OnClick Event

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?

    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!

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.

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, fe jQuery.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM