skip to Main Content

I have this calorie calculator page, and everything is on a single page(PHP, HTML, Javasript). I am trying to store all the form values into the database with the code below,and it works fine except the values of the spans in the div with results class, I have no idea how to store them. These are the results I am trying to store :

<div class="results">
        <div id="calc-target-gain">
            To Gain Weight:<br>
            <span>2700 calories</span>
        </div>
        <div id="calc-target-maintain">
            To Maintain:<br>
            <span>2400 calories</span>
        </div>
        <div id="calc-target-lose">
            To Lose Weight:<br>
            <span>1900 calories</span>
        </div>
    </div>

This is the full code:

<?php
    if( isset(
        $_POST['submit'],
        $_POST["gender"],
        $_POST["age"],
        $_POST["height"],
        $_POST["weight"],
        $_POST["calc-target-gain"],
        $_POST["calc-target-maintain"],
        $_POST["calc-target-lose"],
        $_POST["type"]
    )) {
        
        require 'connect.php'; 
        
        # prepare data for insert - in same order as columns in sql below.
        $args=array(
            $_POST["type"],
            $_POST["gender"],
            $_POST["weight"],
            $_POST["height"],
            $_POST["age"],
            $_POST["calc-target-gain"],
            $_POST["calc-target-maintain"],
            $_POST["calc-target-lose"]
            
        );
        # create a string of variable type identifiers for the prepared statement.
        $types=str_repeat( 's', count( $args ) );
        
        # prepare the sql command with placeholders
        $sql='INSERT INTO calculators 
        ( cType, gender, weight, height, age, cResult, toGainResult, toMaintainResult, toLoseResult, bmiCategory)
        VALUES
        ( ?,?,?,?,?,"0",?,?,?,"null")';
            
        $stmt=$conn->prepare( $sql );
        $stmt->bind_param( $types, ...$args );
        $stmt->execute();
        echo "<script> window.location.assign('calorie_calculator.php'); </script>";
        $stmt->close();
        $conn->close();
    }
?>
<!doctype html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSS -->
    <link rel="stylesheet" href="style.css">

    <title>Simple Calorie Calculator using JavaScript - @code.scientist x @codingtorque</title>
</head>

<body>
    <!-- Further Code Herre -->   
    <div id="bmr-calculator" class="wrapper">
    
    <form id="CalForm" method="POST" style="margin: 5vh 20vw;" onreset="formReset" >
    <div class="calculator">
        <div class="choose-gender">
            <div class="segmented-control"><input id="calc-gender-male" type="radio" name="gender" value="male"
                    checked=""><label for="calc-gender-male">Male</label></div>
            <div class="segmented-control">
                <input id="calc-gender-female" type="radio" name="gender" value="female"><label
                    for="calc-gender-female">Female</label>
            </div>
        </div>
        <label for="calc-age" id="calc-age_value">Age: 25</label>
        <input id="calc-age" type="range" name="age"value="25" min="13" max="100">
        <label for="calc-height" id="calc-height_value">Height: 180cm</label>
        <input id="calc-height" type="range" name="height" value="180" min="80" max="250">
        <label for="calc-weight" id="calc-weight_value">Weight: 80kg</label>
        <input id="calc-weight" type="range" name="weight" value="80" min="40" max="200">
        <label for="calc-walking" id="calc-walking_value">Walking: 2 hours per week</label>
        <input id="calc-walking" type="range" name="activity"value="2" min="0" max="50">
        <label for="calc-cardio" id="calc-cardio_value">Cardio: 1 hour per week</label>
        <input id="calc-cardio" type="range" name="exercise" value="1" min="0" max="50">
        <input type="hidden" id="type" name="type"value="Cal" >
    </div>
    <div class="results">
        <div id="calc-target-gain" name="calc-target-gain">
            To Gain Weight:<br>
            <span>2700 calories</span>
        </div>
        <div id="calc-target-maintain">
            To Maintain:<br>
            <span>2400 calories</span>
        </div>
        <div id="calc-target-lose">
            To Lose Weight:<br>
            <span>1900 calories</span>
        </div>
    </div>
    
    <input type="submit" value="Submit" name="submit" id="submit"class="btn btn-skin btn-sm">
    </form>
</div> 
    <script src="https://code.jquery.com/jquery-3.6.3.js"
        integrity="sha256-nQLuAZGRRcILA+6dMBOvcRh5Pe310sBpanc6+QBmyVM=" crossorigin="anonymous"></script>



    <script>
        $(".calculator input").on("input change", function (event) {
    var parameterName = $(this).attr("id").split("calc-")[1];
    var centimeters = $(this).val()

    switch (parameterName) {
        case "height":
            $("#calc-height_value").html("Height: " + centimeters + " cm");
            break;
        case "weight":
            var kg = $(this).val();
            $("#calc-weight_value").html("Weight: " + kg + " kg");
            break;
        case "age":
            $("#calc-age_value").html("Age: " + $(this).val());
            break;
        case "cardio":
            $("#calc-cardio_value").html("Cardio: " + $(this).val() + " hours per week");
            break;
        case "walking":
            $("#calc-walking_value").html("Walking: " + $(this).val() + " hours per week");
            break;
    }

    var height = parseInt($("#calc-height").val(), 10);
    var age = parseInt($("#calc-age").val(), 10);
    var weight = parseInt($("#calc-weight").val(), 10);
    var walking = parseInt($("#calc-walking").val(), 10);
    var cardio = parseInt($("#calc-cardio").val(), 10);
    var gender = $(".calculator input[name='gender']:checked").val();

    // The Harris–Benedict equations revised by Mifflin and St Jeor in 1990: 'A new predictive equation for resting energy expenditure in healthy individuals'
    var bmr = parseInt(10 * weight + 6.25 * height - 5 * age, 10) + (gender === "male" ? 5 : -161);
    bmr = bmr * 1.2;
    bmr += walking * 60 * (.03 * weight * 1 / 0.45) / 7;
    bmr += cardio * 60 * (.07 * weight * 1 / 0.45) / 7;
    bmr = Math.floor(bmr);

    var targetGainWeight = Math.round((bmr + 300) / 100) * 100;
    var targetMaintain = Math.round((bmr) / 100) * 100;
    var targetLoseWeight = Math.round((bmr - 500) / 100) * 100;

    $("#calc-target-gain span").html(targetGainWeight );
    $("#calc-target-maintain span").html(targetMaintain + " calories");
    $("#calc-target-lose span").html(targetLoseWeight + " calories");
});
    </script>
</body>

</html>

I’ve tried to put a name on divs before the span like this:
name="calc-target-gain", i tried the same on the span itself, but it didnt work also.

please advise if you require further clarification

2

Answers


  1. I don’t really understand what the goal would be. I couldn’t find the URL in your code where you want to send the data. (Maybe calorie_calculator.php?)

    If you send data using a "form" and not with the help of JavaScript, you can only use input fields. However, you can use a "hidden" field to transmit things like CSRF tokens or other IDs.

    More information: <input type="hidden">

    I prefer using sending processes declared in JavaScript.

    If you want to pass a larger dataset beyond the input fields in the request, it needs to be associated with the request.

    You can also send a request using native JavaScript with the fetch method.

    More information: Fetch API

    For example:

    function sendFormByFetch() {
      // YOUR CALCULATIONS
      // ... [HERE] ...
    
      // USING FETCH API, and can use your calculated variables
    
      // 1.) declare what we want to send
      let data = {
        targetGainWeight: targetGainWeight,
        targetMaintain: targetMaintain,
        targetLoseWeight: targetLoseWeight,
      };
    
      // 2.) send "data" to url (can set method and headers)
      fetch("/calorie_calculator.php", {
        method: "POST",
        headers: {
          'Content-Type': 'application/json'
        }, 
        body: JSON.stringify(data)
      })
      // 3.) interpret the received response
      .then(res => {
        console.log("Request complete! response:", res);
      });
    }
    

    In this case, the button needs to be told to execute this function instead of performing the form event.

    <button id="myButton" onclick="sendFormByFetch()">Click Here</button>
    
    Login or Signup to reply.
  2. You can use a hidden input element, combined with JavaScript to pass the data to the form.

    const input = document.getElementById("test-input")
    const div = document.getElementById("span-container")
    const span = div.getElementsByTagName('span')[0]
    
    input.value = span.innerText
    console.log(input.value)
    <input type="hidden" id="test-input" name="test-input">
    <div id="span-container">
      <span>Hello, World!</span>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search