1

Use ajax to pass the value to the back-end, then put the passed value into the session in the back-end, and then use the value of the session in the front end. However, the session is only useful when it is submitted for the first time. No matter how many times the session is submitted later, the stored value is only the value of the first time.

document.php:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./js/jquery-3.6.0.js"></script>
</head>
<body>
    <select name="sreachmsg" id="sreachmsg">
        <option value="1">First thing</option>
        <option value="2">The second thing</option>
        <option value="3">The third thing</option>
        <option value="4">The fourth thing</option>
        <option value="5">The fifth thing</option>
    </select>
    <button id="sreach">search</button>
    <div id="session_val">
    <?php
        session_start();
        $rel = $_SESSION['rel'];
        include('conn.php');
        //取数据库数据
        $res = mysqli_query($conn,"SELECT * FROM test where id='$rel'");
        if($res){
            while($row = mysqli_fetch_assoc($res)){
    ?>
                <tr>
                    <td><?php echo $row["msg"] ?></td>
                </tr>
    <?php
            }
        }
    ?>
</div>
    <script>
        $(document).ready(function(){
            $("#sreach").click(function(){
                var param = $("#sreachmsg").val();
                $.ajax({
                    url: './ajax.php',
                    data: {param:param},
                    type: 'POST',
                    dataType: 'json',
                    success: function(e){
                        console.log(e);
                    }
                });
            });
        });
        
    </script>
</body>
</html>

ajax.php:

<?php
$x=$_POST['param'];
header('Content-Type:application/json');
session_start();
$_SESSION['rel'] = $x;
 
$raw_date = array('code' => '1','msg' => $_SESSION['rel']);
 
$res_date = json_encode($raw_date);
echo $res_date;
?>

How to make the value stored in the session update with the submission?

1
  • the first thing you should do is to start writing php with debug on. The code, like you are showing it, will throw a Warning: Cannot modify header information - headers already sent Commented Apr 27, 2022 at 0:58

1 Answer 1

2

When developing web apps you are working with two distinct, and separate, processing/rendering systems: one is on the server, and the other is on the client. Each system processes different parts of the code, and have limited channels of communication between them.

PHP is executed on the server (back-end).

HTML and Javascript are processed/rendered on the client (front-end/browser).

When the client, using a browser, calls for a page containing PHP, the PHP is first processed on the server then the resulting HTML code, CSS, Javascript, and text content is sent to the browser, as unrendered, unprocessed text. The browser then executes Javascript, renders CSS and HTML, and displays text.

Your Document file, document.php—containing PHP, HTML, and Javascript—when requested by the client, first gets processed by the PHP processor on the server where only the PHP is processed, and the PHP code is replaced with the results of that processing. After that only HTML, Javascript, and text is sent to the browser. No PHP code is sent to the front-end. What your browser receives does not contain PHP code and, therefore, cannot process the PHP code. Your browser does not "see" the PHP session variable $_SESSION['rel'].

The document.php file would have to be reloaded in the browser, i.e., re-requested from the server, in order for the PHP to execute on the server and the value of the PHP session variable to be returned to the browser and displayed in the div element in your HTML page.

Since you're using XHR (Ajax), to send and receive data to and from the server, the HTML page, already loaded in the browser, is not reloaded—only the value of the PHP session variable, when the page was first called and the PHP was processed on the server, are displayed in the div element. (For this reason it appears to you the PHP session variable is not getting updated, but it actually is. If you open your browser console you'll see the data returned to the ajax call is the same as the form data sent to the server, and the updated server-side PHP session variable.)

Your document.php as rendered in the browser, without reloading, successfully posts your form data to to your ajax.php file on the server. The PHP in this file is processed on the server and a JSON response is returned, still without reloading, to the HTML page's ajax call.

Since you're not reloading your page in the browser you must use Javascript to process and display this response in your HTML div tag.

You have two options:

  1. Put all the PHP code in the main HTML document and reload it by POST'ing the form data back to itself. In this case don't use Javascript/XHR/Ajax, or...

  2. Move all your PHP code to ajax.php and use only XHR (Ajax) and Javascript to retrieve data from the server and update the HTML file.


OPTION 1

document.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form action="document.php" method="post">
        <select name="searchmsg">
            <option value="1">First thing</option>
            <option value="2">The second thing</option>
            <option value="3">The third thing</option>
            <option value="4">The fourth thing</option>
            <option value="5">The fifth thing</option>
        </select>
        <input type="submit" value="search">
    </form>
    <div>
        <table>
<?php
    session_start();
    $_SESSION['rel'] = (isset($_POST['searchmsg']))? $_POST['searchmsg']: 0;
    $rel = $_SESSION['rel'];
    include('conn.php');
    //取数据库数据
    $query = sprintf(
        "SELECT * FROM test where id='%s'",
        mysqli_real_escape_string($mysqli, $rel)
    );
    $res = mysqli_query($conn, $query);
    if($res){
        while($row = mysqli_fetch_assoc($res)){
?>
                <tr>
                    <td><?php echo $row["msg"] ?></td>
                </tr>
<?php
        }
    }
?>
    </table>
</div>
</body>
</html>

OPTION 2

document.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./js/jquery-3.6.0.js"></script>
</head>
<body>
    <select name="searchmsg" id="searchmsg">
        <option value="1">First thing</option>
        <option value="2">The second thing</option>
        <option value="3">The third thing</option>
        <option value="4">The fourth thing</option>
        <option value="5">The fifth thing</option>
    </select>
    <button id="search">search</button>
    <div id="searchdiv">
      <table>
          <tr>
              <td>make selection to search</td>
          </tr>
      </table>
   </div>
    <script>
        $(document).ready(function(){
            $("#sreach").click(function(){
                var param = $("#searchmsg").val();
                $.ajax({
                    url: './ajax.php',
                    data: {param:param},
                    type: 'POST',
                    dataType: 'json',
                    success: function(e){
                        console.log(e);
                        table = document.querySelector('#searchdiv table');
                        table.innerHTML = '';
                        $.each(e, function(i, item){
                            var row = table.insertRow();
                            var cell = row.insertCell();
                            cell.innerHTML = item.msg;
                        });

                    }
                });
            });
        });
        
    </script>
</body>
</html>

ajax.php

$x=$_POST['param'];
header('Content-Type:application/json');
session_start();
$_SESSION['rel'] = $x;
 
$rel = $_SESSION['rel'];
include('conn.php');
//取数据库数据
$query = sprintf(
    "SELECT * FROM test where id='%s'",
    mysqli_real_escape_string($mysqli, $rel)
);
$res = mysqli_query($conn, $query);
$raw_date = array();
if($res){
    while($row = mysqli_fetch_assoc($res)){
        $raw_date[] = array('code' => $row['code'],'msg' => $row['msg']);
    }
}
 
$res_date = json_encode($raw_date);
echo $res_date;
Sign up to request clarification or add additional context in comments.

7 Comments

The value returned to Ajax in the background is indeed updated with the submission of the form, but the value of session ['rel '] in PHP in the front end has not changed. How can it change with it?
The front-end does not receive the PHP code. The server (you call background) processes the PHP and replaces it with the resulting values. When using Ajax, you must use Javascript to update the div tag in your HTML file. Have you tried making the changes I recommended?
I tried your code, which is really useful, but it covers my PHP code. I don't want the value returned by the server to be printed in Ajax. I need it to be printed in PHP in the front end, because I need this value to be stored in PHP in the front end for subsequent judgment.
Thanks for accepting my answer. If by "front-end" you mean "execute PHP in the browser", it's impossible—Javascript is your only option. However, if you load another page from the server, or if you reload this page, you will have access to your PHP session variable. OR you can use another Javascript Ajax call to get the current PHP session variable from the server.
Let me ask another way. I get the selected value through the first tag select to determine the content displayed by the next tag table
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.