1

I want to save multiple variables to database, but most of the variable are calculated using java-script/jquery. so i have used .js/ajax and .php to do so but i am getting error on doing this. here is my code example-

JS/Jquery-

$(function(){
  $("#btn").on('click', function() {
    var name =  $("#myname").val();
    var yoursex = $("input[name='gender']:checked").val();
    var date = new Date($('#dob').val());
    var c_age = calc_age();
    var social_age = calcSocialAge();

$.post("insert_data.php", {
    name: name,
    sex: yoursex,
    dob: date,
    crono_age: c_age,
    social_age: social_age
},
      function(data, status){
          alert("Data: " + data + "\nStatus: " + status);
      });
});
});

insert_data.php

<? php  
include_once('connect-mysql.php') ;

      $name = $_post['name'];
      $sex = $_post['sex'];
      $dob = $_post['dob'];
      $c_age = $_post['crono_age'];
      $s_age = $_post['social_age'];



     $sql = " INSERT INTO `patient_info` (`pt_id`, `pt_name`, `pt_gender`, `Pt_dob`, `pt_C_age`, `pt_s_age`)
    VALUES ('', $name,$sex, $dob, $c_age, $c_age, $s_age );";

     ?>

when i am applying this code but getting the error like below -

Data: Connected successfully
Notice: Undefined variable: _post in E:\xampp\htdocs\insert_data.php on line 4 to 8

Status: success

I am quite new to AJAX and PHP please help to resolve the issue.

Amit Soni
  • 94
  • 1
  • 1
  • 6

2 Answers2

1

$_post is not $_POST Change all to $_POST, and also check value

  $name = isset($_POST['name'])?$_POST['name']:'';
  $sex = isset($_POST['sex'])?$_POST['sex']:'';
  $dob = isset($_POST['dob'])?$_POST['dob']:'';
  $c_age = isset($_POST['crono_age'])?$_POST['crono_age']:'';
  $s_age = isset($_POST['social_age'])?$_POST['social_age']:'';

And date is object not any string value as you are expecting like Y-m-d or d-m-Y, it is something like Date 2017-12-23T07:18:08.909Z here

var date = new Date($('#dob').val());//be sure about date value

You are not using quotes to insert string type value in your query, But I suggest to insert use mysqli or pdo. Here are some link to learn about mysqli:

mysqli_prepare

mysqli_stmt_bind_param

Prepared Statements in MySQLi

freelancer
  • 1,174
  • 5
  • 12
0

Could it be as simple as using $_POST['name'] instead of $_post['name'] ? Those superglobals are case-sensitive.

Also, you should do some kind of error checking, or checking to see if one or more fields were left blank. isset($_POST['name']) and empty($_POST) will help you with that.

Tanner Babcock
  • 3,232
  • 6
  • 21
  • 23