How to make the value stored in the PHP session update with the Ajax submission

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;

Leave a Comment