Assy Assy - 1 year ago 104
jQuery Question

Submit Form PHP and Jquery function to display data

I am trying to submit form data in to database, and then retrieve a field from database to calculate the BMI, The INSERT and SELECT query are working fine but the jquery function is on submit and the form, so only the form is submitting and jquery not working. How can i get the form to submit and work out the BMI. This is what i currently have:

if(isset($_POST['submit']) && $_POST['submit']=="submit"){
$userid = $_SESSION['userid'];
$sql="SELECT 1 FROM userDetails WHERE userid = $userid";


if($rs === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
else {
$rows_returned = $rs->num_rows;
$weight = mysqli_real_escape_string($conn, trim($_POST['eWeight']));
$time = mysqli_real_escape_string($conn, trim($_POST['gym']));

$query = "INSERT INTO gymTime (userid, timeSpent, newWeight) VALUES
('$userid','$time', $weight)";

if (mysqli_query($conn, $query)) {

$query = "SELECT height FROM userDetails WHERE userid = $userid";

$result = mysqli_query($conn, $query);

$v = NULL;

while($row = mysqli_fetch_assoc($result))
$v = (int)$row["height"];



else {
echo "Error: " . $result . "<br>" . mysqli_error($conn);

The BMI script

var myHeight= "<?php echo $v; ?>";

$( ".bmi" ).on( "click", function() {
// prevents default submission of form


function getBMI(){
// get the values from the input box
var myweight= $("#eWeight").val();
var myBmi = myweight/(myHeight/100 * myHeight/100);

function displayBMI(myBmi){
$(".showBMI" ).html(" Your BMI is: " + myBmi);

HTML form:

<form class="form1" name="bmi" id="formm" method="POST"

<label for="eWeight">Enter Weight: </label> <input type="number"
id="eWeight" name="eWeight" required/>

<label for="gym">Enter Time at Gym: </label> <input type="number"
id="gym" name="gym" required/>
<input class="submit" name="submit" type="submit" id="submit" value="submit"/>

<div class="showBMI"></div>

The problem is the form is submitting but not JQuery because that is based on click. Any help would be much appreciated.

Answer Source

Just prevent form submit by catching submit event and preventing default behaviour.

And then if execution is success and desired data returned call rest of code.

Check this code:

$(function() {
   function displayBMI(bmi){
     $(".showBMI").html("Your BMI is: " + bmi);

   var $form = $("#formm");

   $form.submit(function(e) {

       url: $form.attr('action'),
       type: $form.attr('method'),
       data: $form.serializeArray(),
       success: function(response) {
         if(typeof response === 'string') {
           response = $.parseJSON(response); // because I don't know how is Your code, and headers, so I'll be accurate and parse json response if it's string

         if(!response.success) {
           if(response.message) {


Also Your php code is ugly.

You do unnecessary database requests,

You do queries without limitation,

You do not have concrete style: mysqli_* or mysqli::* ?

You echo $sql query and sql error codes as an answer, normal user does not need them, bad guys use it for vulnerabilities, try not to show errors to user manually.

Anyway, try this code:

 if(!session_id()) {

 if(isset($_POST['submit'])){ // if it was form submission

    $userid = isset($_SESSION['userid'])? (int)$_SESSION['userid'] : false; // take userid from session

    if(!$userid) {
      // seems like there is no userid param in session array, it means user is not autheticated/authorized
      echo json_encode(array("success" => false, "message" => "Unauthorized!"));

    // checking if user exist, if not stop execution
    $q = "SELECT 1 FROM userDetails WHERE userid = ".$userid." LIMIT 1";
    $q = $conn->query($q);
    if($q->num_rows == 0) {
      echo json_encode(array("success" => false, "message" => "User not found"));

    // inserting data
    $weight = $conn->real_escape_string(trim($_POST['eWeight']));
    $time = $conn->real_escape_string(trim($_POST['gym'])); 
    $q = "
     INSERT INTO gymTime 
     (userid, timeSpent, newWeight) 
     (".$userid.",'".$time."', '".$weight."')";

    // getting user data and calculating bmi
    $q = "SELECT height, weight FROM userDetails WHERE userid = ".$userid." LIMIT 1";
    $record = $conn->query($q)->fetch_array(MYSQLI_ASSOC);

    // here calculate bmi
    $record['bmi'] = $record['weight']/ pow($record['height']/100, 2);

    echo json_encode(array("success" => true, "data" => $record));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download