javascript - The sessions only store data for a second before being changed the last sessions value
When I click theSort By Date Created
button, the stringdate
is passed to the functionsort()
and alert 1 (see code) prints the stringdate
.
The stringdate
is stored in the session in the firstif
statement and the alert 2 printsdate
. The issue isdate
is only being stored temporarily and alert 3 always alertsservice
, no matter the type. If I change the order of the if statements, the last if statement's string somehow always is stored in the session.
<?php session_start(); ?>
<html>
<head>
<script>
function sort(type){
alert('<?php echo $_SESSION['sort']; ?>'); ///ALERT 1
if (type == 'date'){
<?php $_SESSION['sort'] = 'date'; ?>
alert('<?php echo $_SESSION['sort']; ?>'); ///ALERT 2
}
else if (type == 'cost'){
<?php $_SESSION['sort'] = 'cost'; ?>
alert('<?php echo $_SESSION['sort']; ?>');
}
else if (type == 'service'){
<?php $_SESSION['sort'] = 'service'; ?>
alert('<?php echo $_SESSION['sort']; ?>');
}
alert('<?php echo $_SESSION['sort']; ?>'); ///ALERT 3
}
</script>
</head>
<body>
<input type="button" onclick="sort('date');" value="Sort By Date Created">
<input type="button" onclick="sort('cost');" value="Sort By Cost">
<input type="button" onclick="sort('service');" value="Sort By Service">
</body>
</html>
Answer
Solution:
You are confused about the difference between client side and server side code. You have essentially written the following code:
PHP does not respect your javascript
if
statements. PHP will just compile into a static web page which is the latter part of the code I have written.I feel an answer trying to explain the difference between the client-side and server-side code is a little broad and long-winded for StackOverflow, but there are plenty resources out there on that topic.