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(); ?>

   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

  <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">



You are confused about the difference between client side and server side code. You have essentially written the following code:

    $_SESSION['sort'] = 'date';
    $_SESSION['sort'] = 'cost';
    $_SESSION['sort'] = 'service';
if (type == 'date'){

    alert('service'); ///ALERT 2
else if (type == 'cost'){

else if (type == 'service'){


PHP does not respect your javascriptif 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.

People are also looking for solutions to the problem: php - SQL get nearest date record


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.