POST 方法不将数据从 JavaScript 发送到 PHP 文件

问题描述 投票:0回答:1

我在本地存储中存储了一些数据,我想将其发送到数据库。这是JS代码:

function sendData(){
          let input = 'new input';
          localStorage.setItem('spins', input);
          // Get user_id from session or wherever it's stored
          var user_id = <?php echo isset($_SESSION['user_id']) ? $_SESSION['user_id'] : 'null'; ?>;

          if (user_id) {
            var value1 = localStorage.getItem('data');
            var value2 = localStorage.getItem('spins');

            var xhr = new XMLHttpRequest();
            xhr.open('POST', 'update_values_to_database.php', true);
            xhr.setRequestHeader('Content-Type', 'application/json');
            xhr.onreadystatechange = function() {
              if (xhr.readyState === 4 && xhr.status === 200) {
                try {
                  var data = JSON.parse(xhr.responseText);
                  if (data.success) {
                      localStorage.setItem('data', data.data);
                      localStorage.setItem('spins', data.spins);
                      
                  } else {
                      console.error('Failed to retrieve values from the database.');
                  }
                } catch (error) {
                  // Code to handle the error
                  console.error('An error occurred:', error.message);
                  window.location.href = "update_values_to_database.php";
                }     
              }
              };
          }
            xhr.send(JSON.stringify({ user_id: user_id, value1: value1, value2: value2 }));
          }

`

这就是 PHP

<?php
include("database.php");

// Retrieve data from the POST request
var_dump($_REQUEST);
$user_id = $_POST['user_id'];
$value1 = $_POST['value1'];
$value2 = $_POST['value2'];

// Update values in the database for the given user_id
// Modify this query according to your database schema
$query = "UPDATE users SET data = ?, spins = ? WHERE user_id = ?";
$stmt = mysqli_prepare($conn, $query);
mysqli_stmt_bind_param($stmt, 'ssi', $value1, $value2, $user_id);
if (mysqli_stmt_execute($stmt)) {
    echo json_encode(array('success' => true));
} else {
    echo json_encode(array('success' => false));
}
?>

JS代码文件和PHP代码文件在同一个目录下。我不知道我做错了什么。有人能告诉我错误可能是什么吗? 预先感谢。

我尝试记录错误,它说“user_id”、“value1”和“value2”键未定义,当我 var_dump $_REQUEST 时,它返回一个空数组。当我确保发送到 PHP 文件的所有变量都已正确定义时。

javascript php database post phpmyadmin
1个回答
0
投票

到 mysqli 数据库将所有内容转换为字符串, json 或内爆所有数组

$value1 = implode('',$_POST['value1']);
$value2 = implode('',$_POST['value2']);
© www.soinside.com 2019 - 2024. All rights reserved.