Reputation: 511
I have some implicit PHP functions which are to be called on particular front-end events; such as button
onclick
s. By doing so this should modify my PHP SESSION
variable accordingly. However, both functions, setAlan()
and setMark()
, seem to be getting called even if I just want the first one to execute.
<?php
session_start();
function setAlan() {
$_SESSION['passed_user']='alan';
}
function setMark() {
$_SESSION['passed_user']='mark';
}
?>
<script>
function getAlan() { $(document.body).append('<?php setAlan(); ?>'); }
function getMark() { $(document.body).append('<?php setMark(); ?>'); }
function show() { alert(' <?php echo "{$_SESSION['passed_user']}" ?> '); }
</script>
<div class="pod">
<div class="pod_title"><h2>Select a User</h2></div>
<div>
<input type="button" onclick="getAlan();" value="alan">
<input type="button" onclick="getMark();" value="mark">
<input type="button" onclick="show();" value="show">
</div>
</div>
I don't understand why setMark()
is being called automatically? By what I've written, I believe I am only defining the PHP functions, not calling them; I use JS for that. Am I missing something? Thanks in advance!
Upvotes: 0
Views: 98
Reputation: 578
PHP is executed first, server side. Once PHP is done, your browser ( client ) gets the result, Javascript is executed on the client, so after PHP is done.
You can't mix javascript and PHP as you did with:
<script>
function getAlan() { $(document.body).append('<?php setAlan(); ?>'); }
function getMark() { $(document.body).append('<?php setMark(); ?>'); }
function show() { alert(' <?php echo "{$_SESSION['passed_user']}" ?> '); }
</script>
However you can use Javascript to call some server side PHP script with ajax ( Asynchronous JavaScript and XML ).
http://www.w3schools.com/ajax/default.ASP
Upvotes: 1