简体   繁体   English

将用户输入保存到PHP,然后在Javascript函数中使用

[英]Saving User Input to PHP to then Use in Javascript Function

Looking for a solution to an issue that I am having. 寻找解决我遇到的问题的方法。 My PHP file is able to store a date and time from a user's input. 我的PHP文件能够根据用户输入存储日期和时间。 However, once the date is stored, it is no longer accessible to be used in my Javascript function. 但是,一旦存储了日期,就不再可以在Javascript函数中使用它。

I am just lost on how data is processed step by step. 我只是迷路于如何逐步处理数据。 How would I extract stored data in my database to use in my Javascript function? 如何提取数据库中存储的数据以在Javascript函数中使用?

UPDATE: ADDED CODE 更新:添加代码

PHP: Simply stores input, and shows it was stored PHP:仅存储输入,并显示已存储

    <?php
// ONLY Process Form if $_POST is NOT Empty
if ( ! empty( $_POST ) ) {

  // Connect to MySQL
  $mysqli = new mysqli( 'hn', 'un', 'pw', 'db' );

  // Check Our Connection
  if ( $mysqli->connect_error ) {
    die( 'Connect Error: ' . $mysqli->connect_errno . ': ' . $mysqli->connect_error );
  }

  // Insert Our Data
  $sql = "INSERT INTO table ( mydate ) VALUES ( '{$mysqli->real_escape_string($_POST['myDate'])}' )";
  $insert = $mysqli->query($sql);

  // Print Response from MySQL
  if ( $insert ) {
    echo "Success! Row ID: {$mysqli->insert_id}";
  } else {
    die("Error: {$mysqli->errno} : {$mysqli->error}");
  }

  // Close Connection
  $mysqli->close();
}
?>

HTML: Just a form HTML:只是一种形式

  <html>
  <head>
    <meta charset="utf-8">
    <title>User Form</title>
  </head>
  <script type="text/javascript" src="/displaytimer.js"></script>
  <body>
    <!-- HTML Form -->
    <form class="" action="/index.php" method="post">
      <input type="datetime-local" name="myDate" id="myDate"><br /><br />
      <button id="submit" onclick="clickButton()" value="submit">Submit</button><br /><br />
      <div id="showDate"></div>
    </form>
   </body>
  </html>

JAVASCRIPT: Generates a timer based on users inputed date. JAVASCRIPT:根据用户输入的日期生成一个计时器。 Also accessible on iPhone (found help here on SO for that). 也可以在iPhone上访问(为此可在SO上找到帮助)。 I am sure that there is a simpler way to do this, but I am mainly looking for how to still use the date inputed within var n . 我敢肯定有一种更简单的方法可以做到这一点,但是我主要是在寻找如何仍然使用var n中输入的日期

// get the iso time string formatted for usage in an input['type="datetime-local"']
var tzoffset = (new Date()).getTimezoneOffset() * 60000; //offset in milliseconds
var localISOTime = (new Date(Date.now() - tzoffset)).toISOString().slice(0,-1);
var localISOTimeWithoutSeconds = localISOTime.slice(0,16);

// select the "datetime-local" input to set the default value on
var dtlInput = document.querySelector('input[type="datetime-local"]');

// set it and forget it ;)
dtlInput.value = localISOTime.slice(0,16);

function clickButton() {
  var x = setInterval(function() {
    // Get Date Selected & Convert to ISO
    var n = document.getElementById("myDate").value;
    var d = new Date(n);
    var dISO = d.toISOString();

    // Get Today's Date
    var today = new Date();
    var tS = today.toDateString();
    var tISO = today.toISOString();

    // Calculate Time Left
    var dParse = Date.parse(dISO);
    var tParse = Date.parse(tISO);
    var distance = dParse - tParse;
    // days
    var days = Math.floor(distance / (1000 * 60 * 60 * 24));
    if (days > 0) {
      days = Math.floor(distance / (1000 * 60 * 60 * 24));
    } else {
      days = 0;
    }
    // hours
    var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    if (hours > 0) {
      hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    } else {
      hours = 0;
    }
    // minutes
    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    if (minutes > 0) {
      minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    } else {
      minutes = 0;
    }
    // seconds
    var seconds = Math.floor((distance % (1000 * 60)) / 1000);
    if (seconds > 0) {
      seconds = Math.floor((distance % (1000 * 60)) / 1000);
    } else {
      seconds = 0;
    }

    // Print Distance or Expired Message
    if (days > 0 || hours > 0 || days > 0 || seconds > 0) {
      document.getElementById("showDate").innerHTML = days + " days " + hours + " hours " + minutes + " minutes " + seconds + " seconds ";
    } else {
      document.getElementById("showDate").innerHTML = "The time has expired";
    }
  }, 1000);
}

By using AJAX to submit the form (ie store the date on the server), the page won't reload and so your javaScript code will be executed. 通过使用AJAX提交表单(即在服务器上存储日期),该页面将不会重新加载,因此您的javaScript代码将被执行。
Here is a break down of how it can work: 以下是其工作方式的分解:

  1. The clickButton() JavaScript function gets the values from the input fields of the form. clickButton()JavaScript函数从表单的输入字段获取值。
  2. It then performs the ajax request sending the data to a PHP file ie store_data.php (this will contain the php code which was originally at the top of your page). 然后,它执行ajax请求,将数据发送到PHP文件,即store_data.php(其中将包含最初位于页面顶部的php代码)。
  3. The server processes whats in the PHP file. 服务器处理PHP文件中的内容。 ie inserts the date to the database 即将日期插入数据库
  4. The PHP file echos back whatever data you like to the client (in your case you have success or error). PHP文件将您喜欢的任何数据回传给客户端(如果您遇到成功或失败)。
  5. A callback is performed on the client side where the data (that was echoed) can be retrieved from the server and javaScript code can be executed. 在客户端执行回调,可以从服务器检索(回显的)数据,并可以执行javaScript代码。 Note: The page hasn't reloaded so the myDate input field is still populated. 注意:页面尚未重新加载,因此myDate输入字段仍被填充。

index.html 的index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>User Form</title>
<script type="text/javascript" src="/displaytimer.js"></script>
</head>
<body>
  <!-- HTML Form -->
  <form class="" action="" method="post">
    <input type="datetime-local" name="myDate" id="myDate"><br /><br />
      <button id="submit" onclick="clickButton()" type="button">Submit</button><br /><br />
      <div id="showDate"></div>
  </form>
</body>
</html>

displaytimer.js displaytimer.js

 window.onload = function(){
      // get the iso time string formatted for usage in an input['type="datetime-local"']
      var tzoffset = (new Date()).getTimezoneOffset() * 60000; //offset in milliseconds
      var localISOTime = (new Date(Date.now() - tzoffset)).toISOString().slice(0,-1);
      var localISOTimeWithoutSeconds = localISOTime.slice(0,16);

      // select the "datetime-local" input to set the default value on
      var dtlInput = document.querySelector('input[type="datetime-local"]');

      // set it and forget it ;)
      dtlInput.value = localISOTime.slice(0,16);
    }


    function createXHR(){
      //This function sets up the XMLHttpRequest
      try{
        return new XMLHttpRequest();
      }catch(e){
        //to support older browsers
        try{
          return new ActiveXObject("Microsoft.XMLHTTP");
         }catch(e){
           return new ActiveXObject("Msxml2.XMLHTTP");
         }
      }
    }

    function clickButton(){
      //The form has been submitted.
      //Get the value of the myDate field from the form
      var myDate = document.getElementById('myDate').value;
      //set up the ajax request
      xmlhttp = createXHR();
      xmlhttp.onreadystatechange = ajaxCallback; //name of our callback function here
      //Ive called the php file store_data.php but you can call it whatever you like.
      xmlhttp.open("POST", "store_data.php" ,true);
      xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      //send our variables with the request
      xmlhttp.send("myDate=" + myDate);
    }

    function ajaxCallback(){
      //this function will be executed once the ajax request is completed
      if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
        //The ajax request was successful.
        //we can now get the response text using xmlhttp.responseText. This will be whatever was echoed in the php file
        var data = xmlhttp.responseText; 
        //In your case "data" will either be "Success! Row ID: ..." OR "Error: ....." so you can do checks here.
        //For demonstration I will just continue with the rest of your code.

        var x = setInterval(function() {
          // Get Date Selected & Convert to ISO
          var n = document.getElementById("myDate").value;
          var d = new Date(n);
          var dISO = d.toISOString();

          // Get Today's Date
          var today = new Date();
          var tS = today.toDateString();
          var tISO = today.toISOString();

          // Calculate Time Left
          var dParse = Date.parse(dISO);
          var tParse = Date.parse(tISO);
          var distance = dParse - tParse;
          // days
          var days = Math.floor(distance / (1000 * 60 * 60 * 24));
          if (days > 0) {
            days = Math.floor(distance / (1000 * 60 * 60 * 24));
          } else {
            days = 0;
          }
          // hours
          var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
          if (hours > 0) {
            hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
          } else {
            hours = 0;
          }
          // minutes
          var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
          if (minutes > 0) {
            minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
          } else {
            minutes = 0;
          }
          // seconds
          var seconds = Math.floor((distance % (1000 * 60)) / 1000);
          if (seconds > 0) {
            seconds = Math.floor((distance % (1000 * 60)) / 1000);
          } else {
            seconds = 0;
          }

          // Print Distance or Expired Message
          if (days > 0 || hours > 0 || days > 0 || seconds > 0) {
            document.getElementById("showDate").innerHTML = days + " days " + hours + " hours " + minutes + " minutes " + seconds + " seconds ";
          } else {
            document.getElementById("showDate").innerHTML = "The time has expired";
          }
        }, 1000);   

      }
    }

store_data.php store_data.php

<?php
// ONLY Process Form if $_POST is NOT Empty
if ( ! empty( $_POST ) ) {

  // Connect to MySQL
  $mysqli = new mysqli( 'hn', 'un', 'pw', 'db' );

  // Check Our Connection
  if ( $mysqli->connect_error ) {
    die( 'Connect Error: ' . $mysqli->connect_errno . ': ' . $mysqli->connect_error );
  }

  // Insert Our Data
  $sql = "INSERT INTO table ( mydate ) VALUES ( '{$mysqli->real_escape_string($_POST['myDate'])}' )";
  $insert = $mysqli->query($sql);

  // Print Response from MySQL
  if ( $insert ) {
    echo "Success! Row ID: {$mysqli->insert_id}";
  } else {
    die("Error: {$mysqli->errno} : {$mysqli->error}");
  }

  // Close Connection
  $mysqli->close();
}
?>

UPDATE: 更新:

If you want to send multiple variables back from the PHP file you can create an associative array and use json_encode as follows: 如果要从PHP文件发送回多个变量,则可以创建一个关联数组,并使用json_encode,如下所示:

store_data.php: store_data.php:

$responseData = array(); //create a PHP array
$responseData['status'] = "success"; 
$responseData['myDateSubmitted'] = $_POST['myDate']; //store the date that was submitted into a variable to send back
echo json_encode($responseData); //echo the response data back to the client

displaytimer.js displaytimer.js

function ajaxCallback(){
  //this function will be executed once the ajax request is completed
  if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
    //The ajax request was successful.
    //we can now get the response text using xmlhttp.responseText. 
    //parse the response text as JSON because we used json_encode in our PHP file.
    var jsonData = JSON.parse(xmlhttp.responseText);
    console.log(jsonData.myDateSubmitted); //check one of our variables
    //Rest of your code here
  }

} }

You should avoid submitting data with a POST, this way the page will not reload, so you don't need spitting back anything. 您应该避免使用POST提交数据,这样就不会重新加载页面,因此您不需要吐出任何东西。

Use AJAX to send myDate to the backend to make it persistent on the DB. 使用AJAX将myDate发送到后端,使其在数据库上持久存在。

Simply speaking, you should convert your PHP code in a basic backend REST service; 简而言之,您应该在基本的后端REST服务中转换PHP代码; avoid sticking PHP code with the HTML page and process posted data, this is a very old way of doing things. 避免在HTML页面上粘贴PHP代码并处理发布的数据,这是一种非常古老的处理方式。

Use PHP for the backend and JS for the frontend. 后端使用PHP,前端使用JS。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM