Daniel Holler Daniel Holler - 3 years ago 135
HTML Question

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

I 2 files: grampermol.php and kemi.html. In kemi.html, I call a javascript function that runs the grampermol.php file when a button is pressed. The issue I'm having is, that I cannot obtain values from the input field in php that is located in the html file.

kemi.html button function:

<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();
?>


I'm getting an error saying that molar_mass doesn't exist.

Answer Source

To do this you want an ajax Jquery call.You must understand first that php is a server side language and the javascript/jquery a client side.At the codes below you will see the kemi.html code first.As you see when you set an input value and then click the button then the Jquery code takes tha input value via ajax post method and send it to grampermol.php page.At the grampermol.php page when you have a valid post superglobal variable-value you get it and then echo it via json_encode() function.The echoed variable send back to the .done ajax method and alert() it. kemi.html code:

 $(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 code:

       <?php

if(isset($_POST['data'])){

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

} ?>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download