Php 文件在单击 <button> 后从 html 文件输入字段中获取数据

Php file fetching data from html file input field after <button> is clicked

我有 2 个文件:grampermol.php 和 kemi.html。在 kemi.html 中,我调用了一个 javascript 函数,该函数在按下按钮时运行 grampermol.php 文件。我遇到的问题是,我无法从位于 html 文件中的 php 中的输入字段获取值。

kemi.html 按钮功能:

<input type="text" name="molar_mass" id="molar_mass" placeholder="Fx CH4" size="20">
<br>
<button style="margin-bottom: 1em; margin-top: 1em;" name="BUTTON_1" onclick="gramsPerMole()" type="submit" class="btn btn-success">Beregn</input>

grampermol.php:

<?php

function calculate() {
   $formula = $_POST['molar_mass'];
}

calculate();
?>

我收到一条错误消息,提示 molar_mass 不存在。

<!-- html form  file -->
<!-- i dont know how your  gramsPerMole() is so this is what i can help you with tell me if it works-->

    <form action="grampermol.php" method="post">
    <input type="text" name="molar_mass" id="molar_mass" placeholder="Fx CH4" size="20"><br>
    <button type="submit" style="margin-bottom: 1em; margin-top: 1em;" name="BUTTON_1" onclick="gramsPerMole()"  class="btn btn-success"> Beregn </button>

    <!--grampermole.php file -->
    <?php
    function calculate() {
       $formula = $_POST['molar_mass'];
     return;`enter code here`
    }
     calculate();
 ?>

要做到这一点,您需要 ajax Jquery call.You 必须首先了解 php 是服务器端语言,而 javascript/jquery 是客户端 side.At 下面的代码你会看到 kemi.html 代码 first.As 当你设置一个输入值然后点击按钮时你会看到 Jquery 代码通过 ajax post 方法,当你有一个有效的 post 超全局变量值时,将它发送到 grampermol.php page.At grampermol.php 页面,然后回显它通过 json_encode() function.The 回显变量发送回 .done ajax 方法和 alert() 它。 kemi.html代码:

 $(document).ready(function (){
       $('#grams').on('click',function (){
       var a=$('#molar_mass').val();       
       $.ajax({
           url: "grampermol.php",
           method:'POST',
           dataType: 'JSON',
           data:{data:a}})           
                   .done(function( msg ) {
           alert( "Data Saved: " + msg );
       
    });
       
   });
   }); 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="molar_mass" id="molar_mass" placeholder="Fx CH4" size="20">
<br>
<button style="margin-bottom: 1em; margin-top: 1em;" name="BUTTON_1" id="grams" type="submit" class="btn btn-success">CLICK</button>

grampermole.php代码:

<?php
if(isset($_POST['data'])){

   $formula = $_POST['data'];
   echo json_encode($formula);

}
?>