How to store javascript values into mysql database? - javascript

I'm trying to store the users BMI score and comments into mysql database. I'm able to store their height and weight but just not their score and bmi comment.
Any suggestions would be appreciated.
<script type="text/javascript">
function Calculate()
{
//Obtain user inputs
var height=Number(document.getElementById("height").value);
var heightunits=document.getElementById("heightunits").value;
var weight=Number(document.getElementById("weight").value);
var weightunits=document.getElementById("weightunits").value;
//Convert all units to metric
if (heightunits=="inches") height/=39.3700787;
if (weightunits=="lb") weight/=2.20462;
if (heightunits=="cm") height/=100;
//Perform calculation
var BMI=weight/Math.pow(height,2);
//Display result of calculation
document.getElementById("output").innerText=Math.round(BMI*100)/100;
var output = Math.round(BMI*100)/100
if (output<18.5)
document.getElementById("comment").innerText = "Underweight";
else if (output>=18.5 && output<=25)
document.getElementById("comment").innerText = "Normal";
else if (output>=25 && output<=30)
document.getElementById("comment").innerText = "Obese";
else if (output>30)
document.getElementById("comment").innerText = "Overweight";
// document.getElementById("answer").value = output;
}
</script>
</head>
<body>
<div>BMI Calculator</div>
<input type="button" value="Calculate" onclick="Calculate(this.form);">
<input type="submit" name="savebmi" value="SaveBMI">
<p class="font-3">Your BMI is: <span name="output" value="output" type="float" id="output" class="textInput"></span></p>
<p class="font-3">This means you are: <span name="comment" type="text" id="comment"></span> </p>

One thing you could do is change your span tags to input tags and then just change your JavaScript to set the value attribute instead of the innerText. Then when you submit the form, it will pass those values to your PHP script.
You can always style your input boxes to match your paragraph text if don't like the appearance of boxes. For example, start with style='border:none.
JavaScript
//Display result of calculation
document.getElementById("output").value=Math.round(BMI*100)/100;
var output = Math.round(BMI*100)/100
if (output<18.5)
document.getElementById("comment").value = "Underweight";
else if (output>=18.5 && output<=25)
document.getElementById("comment").value = "Normal";
else if (output>=25 && output<=30)
document.getElementById("comment").value = "Obese";
else if (output>30)
document.getElementById("comment").value = "Overweight";
// document.getElementById("answer").value = output;
HTML
<p class="font-3">Your BMI is: <input name="output" type="float" id="output" class="textInput" style="border:none" /></p>
<p class="font-3">This means you are: <input name="comment" type="text" id="comment" style="border:none" /></p>

Elements with id output and comment are not input elements but span, so they are not passed to the PHP script.
You should try to pass this via AJAX to your script, then you can add these values to the request.
Example:
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Whatever you want to do with the php response
}
}
req.open("POST", "script.php", true);
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.send("output=" + output + "&weight=" + weight + ...);
Another workaround is to use hidden input elements, but then you should make a function to validate these or make it non-editable.

Here is a solution to fit your question..
//Display result of calculation
var bmi_result = Math.round(BMI*100)/100;
document.getElementById("output").innerText=bmi_result;
document.getElementById("form_output").innerText=bmi_result;
var comment = '';
if (bmi_result<18.5) {
comment = "Underweight";
} else if (bmi_result>=18.5 && output<=25) {
comment = "Normal";
} else if (bmi_result>=25 && output<=30) {
comment = "Obese";
} else if (bmi_result>30) {
comment = "Overweight";
}
document.getElementById("comment").innerText = comment;
document.getElementById("form_comment").innerText = comment;
In your form:
<input type="hidden" id="form_output" name="output" value="">
<input type="hidden" id="form_comment" name="comment" value="">
<input type="button" value="Calculate" onclick="Calculate(this.form);">

Related

validate form for dynamically created inputs count

I am dynamically creating the inputs in the form
I want user to enter at least 'n' elements.
<html lang="en-US">
<head>
<meta name="referrer" content="origin">
<script>
var counter = 0;
var limit = 50;
function addInput(divName, arrName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
var af = "autofocus"
newdiv.innerHTML = "<input id='my-div-"+counter+"' type='text' name='" + arrName + "[]' required autofocus=" + af + ">";
document.getElementById(divName).appendChild(newdiv);
document.getElementById('my-div-'+counter).focus();
counter++;
}
}
function validateForm(){
var frm = document.forms['simples'];
a = parseInt(frm.elements['myInputs_1[]'].length)
var sum = parseInt(frm.elements['myInputs_1[]'].length)
if(parseInt(sum) < 4){
alert("You must write at least 4 sentences ");
return false;
}
}
</script>
</head>
<body>
<form name="simples" action="part.php" align="center" onsubmit="return validateForm()" method="POST">
<div id = "dynamicInputHolder_1">
<b>Emotion </b><input type="text" value="" name="emotion" id="emotion" class="generatedEmotion" readonly>
<input type="hidden" value="" name="uniqueID" id="uniqueID">
<div id="dynamicInput_1">
<textarea rows="5" cols="50" readonly class="floating-box">
John arrived at Sally's house to pick her up. John and Sally were going to a fancy restaurant that evening for a dinner. John was little nervous because he was going to ask Sally to marry him.</textarea>
</div>
<input type="button" value="Add connecting sentences" onClick="addInput('dynamicInput_1', 'myInputs_1');">
</div>
<br>
<input type="submit" value="show me what is next">
</form>
</body>
</html>
The method validateForm() works only if number text boxes are greater than equal to 2, for 0 and 1 it does not work.
Please not that this is minimal example, in real website, I have many such divs collecting input in multiple arrays, so I am summing them over something like:
var sum = parseInt(frm.elements['myInputs_1[]'].length) + parseInt(frm.elements['myInputs_2[]'].length) + parseInt(frm.elements['myInputs_3[]'].length)
but it may happen that few of the arrays are empty.
How do I check that collectively there are atleast n inputs?
frm.elements['myInputs_1[]'] has a different behavior for each of the cases.
for no elements entered, it will be undefined
for 1 element, it only contains that element, so it does not have a length
for two elements onwards it is an object of type RadioNodeList, which is inherited from NodeList and has a length attribute.
so the validate form method changes to:
function validateForm(){
var frm = document.forms['simples'];
ele = frm.elements['myInputs_1[]'];
if(typeof ele === 'undefined'){
alert('no element at all..');
return false;
}
else if(ele.value == ""){
if (ele.length < 4){
alert("You must write at least 4 sentences ");
return false;
}
}
else{
alert('contains one element');
return false;
}
return true;
}
and it works!

what is the correct way to validate form with javascript

should i put "submit" instead "form_name" in the last block of code? what is the correct way?
thanks!
function check() {
var title = document.getElementById("title");
var content = document.getElementById("content");
if (title == "") {
alert("title is required");
return false;
}
if (content == "") {
alert("content is required");
return false;
}
var submit = document.getElementById("form_name");
submit.submit();
}
this is my form
<form action="#" method="post" id="form_name" name="form_name">
<input type="text" name="title" id="title" />
<textarea name="content" id="content" cols="30" rows="10"></textarea>
<input type="submit" value="Submit" id="submit" name="submit" onclick="return check();"/>
</form>
First you are selecting an element and acting like it is the value
var title = document.getElementById("title"); <-- DOM element
if (title == "") { <-- checking the DOM against a string.
You should be using .value to get what was entered.
Next you are submitting the form.... but you clicked on a submit button inside of the form so that will submit the form. So that is not needed.
function check() {
var title = document.getElementById("title").value;
var content = document.getElementById("content").value;
if (!title.trim().length) {
alert("title is required");
return false;
else if (!content.trim().length) {
alert("content is required");
return false;
}
return true
}
And never name anything submit, it just leads to problems.
In most recent browsers you have more power to use
function myFunction() {
var inpObj = document.getElementById("id1");
if (inpObj.checkValidity() == false) {
document.getElementById("demo").innerHTML = inpObj.validationMessage;
}else{
document.getElementById("demo").innerHTML = "";
}
}
<input id="id1" type="number" min="100" max="300" required>
<button onclick="myFunction()">OK</button>
<p id="demo"></p>
Reference:
https://www.w3schools.com/js/js_validation_api.asp

HTML/JS Text recognition variable displayer

I cannot get the <div id="output"> section to display the variable txtOutput or maybe the variable txtOutput is not being defined or changed.
I would appreciate help on re-defining this variable or how to display it. (the empty text box feature works though)
function smartinput() {
var txtInput = document.forms["form"]["inputA"].value;
var txtOutput;
var input = txtInput.value;
if (txtInput == null || txtInput == "") {
alert("Please put text in Input");
return false;
} else if (txtInput == "Hi") {
return output.value = "Hello";
}
document.getElementByID("Output").innerHTML = txtOutput;
}
<p><strong>Note:</strong> The output element is not supported in Edge 12 or Internet Explorer and earlier versions.</p>
<h1> Smart Responder Test 1 </h1>
<form name="form">
<fieldset>
<label> Input: </label>
<textarea cols="30" rows="2" name="inputA" id="txtInput"></textarea>
<p></p>
<input type="button" value="Submit" onclick="smartinput()" />
<p></p>
<label>Output: </label>
<div id="Output"></div>
</fieldset>
</form>
Firstly, you made a typo for method getElementById, correct that.
Secondly, you are defining variable txtOutput but not using it later, rather you use output. Just change output to txtOutput:
function smartinput() {
var txtInput = document.forms["form"]["inputA"].value;
var txtOutput;
var input = txtInput.value;
if (txtInput == null || txtInput == "") {
alert("Please put text in Input");
return false;
} else if (txtInput == "Hi") {
txtOutput= "Hello";
}
document.getElementById("Output").innerHTML = txtOutput;
}
And you don't need txtOutput.value because it is only a variable for result.
Some errors
you should put getElementById in place to ...byID
If it is empty or null, just put it like this !(elem or value)
The output element is not a text area so value will not work. Change it to innerHTML or innerText
TxtInput and input are the same in your code
function smartinput() {
var txtInput = document.forms["form"]["inputA"];
var input = txtInput.value;
var output = document.getElementById("Output");
if (!input) {
alert("Please put text in Input");
return false;
} else if (input == "Hi") {
return output.innerHTML = "Hello";
}
}
<p><strong>Note:</strong> The output element is not supported in Edge 12 or Internet Explorer and earlier versions.</p><h1> Smart Responder Test 1 </h1><form name="form"><fieldset><label> Input: </label><textarea cols="30" rows="2" name="inputA" id="txtInput"></textarea><p></p><input type="button" value="Submit" onclick="smartinput()" /><p></p><label>Output: </label><div id="Output"></div></fieldset></form>

"NaN" result when multiplying more than one value in an array by a number

Note: please pay no attention to my beginnings on the "Decrypt" function, button, etc. It has no relevance towards this question.
I've looked practically everywhere for a fix on here and can't seem to find one due to my kinda strange project. I'm a noob at JavaScript so please tell me anything I could improve on. Here's my project: It's basically a Encrypt/Decrypt message thing based on what key you type in.. When you type in the key, and submit it, it gives the key a value based on it's length and ASCII value:
function submitkey(form) {
keyinp = (form.key.value)
var keyl = keyinp.length
keyasciiout = keyinp.charCodeAt(0)
document.getElementById("asciikeyout").innerHTML =
"<b>" + keyinp + "</b> is your key."
if (keyl > 4) {
keyasciitwo = keyinp.charCodeAt(1)
keyasciithree = keyinp.charCodeAt(2)
keyasciifour = keyinp.charCodeAt(3)
keyasciifive = keyinp.charCodeAt(4)
finalkey = (((keyasciiout + keyasciitwo + keyasciithree + keyasciifour + keyasciifive) / keyl) * 0.5)
}
else { alert("Please choose a new key. It must be 5 or more characters.") }
}
So now you've entered a key and it has a value that plays a role in encrypting/decrypting your messages. Here's the text boxes that you enter in and stuff.
<form name="keyinput">
<input type="text" id="key" name="key">
<br>
<input type="button" name="keysub" id="keysub" value="Submit Key" onclick="submitkey(this.form)">
</form>
<p id="asciikeyout"></p>
<p id="key2"></p>
<br> <br>
<br> <br>
<br> <br>
<form name="field">
<input type="button" name="decryptbutton" onclick="dec(this.form)" value="Decrypt">
<br>
<textarea id="input" rows="4" cols="50" onkeyup="getascii(this.form)" onkeydown="keycheck(this.form)"></textarea>
<br>
<br>
<textarea id="output" rows="20" cols="70" fontsize="18px" readonly></textarea>
</form>
<p id="res2"></p>
By the way, the keycheck() function is just something where if you type in the textbox and don't have anything entered as a key, it will alert you to create a key.
So whenever you type into the input textbox, it runs getascii(this.form), which, btw, just gets the ASCII values of all of the characters you typed and stores them as a variable, in which this case, is "code":
function getascii(form) {
globalinp=(form.input.value)
var str=(form.input.value);
code = new Array(str.length);
for(var i=0;i<str.length;i++){
code[i]=str.charCodeAt(i);
}
encrypt(code)
}
Which, in turn, runs encrypt(), which places the "code" values into an array(i think, this may be the issue. please tell me.):
function encrypt(code) {
sepcode = code.toString().replace(/,/g, " ")
asciiarray = sepcode.split(" ");
arrmult()
}
Which, then again, runs a function called arrmult, which is where the trouble begins (i think).
function arrmult() {
var a = [asciiarray];
var b = a.map((function (x) { return x * finalkey; }).bind(this));
document.getElementById("output").innerHTML =
b
}
The above code I got from this website. What it does is takes each individual value of the array assigned as the variable A, in this case all of the ASCII values of whatever you typed in the box, and multiplies them by a certain value, which I have set as the value of the key. Note: When I replace the variable A with a string of numbers, like this:
var a = [127,93,28];
It seems to be working perfectly fine. But, when I use asciiarray instead, it returns back with a value of "NaN", but only when I do more than ONE character. When I only type one character and have the variable a set as this:
var a = [asciiarray];
It works perfectly fine. But when it updates, and has two or more characters, it results as "NaN" even though the value of asciiarray is the exact same as the numbers above. And when you do reply, please help me realize where to replace what I've done wrong, as I'm a JavaScript complete noob.
If you wish to look at the code completely, here it is. You can even copy and paste it into an HTML file if you wish:
<html>
<body>
<head>
<title>Ascii Encryption</title>
</head>
<script>
var code="test"
var sepcode="test"
var keyinp="test"
var keyasciiout="test"
var finalkey="test"
var globalinp="test"
var globalascarr="test"
var multex="test"
var keyasciitwo="test"
function getascii(form) {
globalinp=(form.input.value)
var str=(form.input.value);
code = new Array(str.length);
for(var i=0;i<str.length;i++){
code[i]=str.charCodeAt(i);
}
encrypt(code)
}
</script>
<script>
function submitkey(form) {
keyinp = (form.key.value)
var keyl = keyinp.length
keyasciiout = keyinp.charCodeAt(0)
document.getElementById("asciikeyout").innerHTML =
"<b>" + keyinp + "</b> is your key."
if (keyl > 4) {
keyasciitwo = keyinp.charCodeAt(1)
keyasciithree = keyinp.charCodeAt(2)
keyasciifour = keyinp.charCodeAt(3)
keyasciifive = keyinp.charCodeAt(4)
finalkey = (((keyasciiout + keyasciitwo + keyasciithree + keyasciifour + keyasciifive) / keyl) * 0.5)
}
else { alert("Please choose a new key. It must be 5 or more characters.") }
}
</script>
<script>
function encrypt(code) {
sepcode = code.toString().replace(/,/g, " ")
asciiarray = sepcode.split(" ");
arrmult()
}
</script>
<script>
function arrmult(none) {
var a = [asciiarray];
var b = a.map((function (x) { return x * finalkey; }).bind(this));
document.getElementById("output").innerHTML =
b
}
</script>
<script>
function dec(form) {
var input = (form.input.value)
var inputdiv = (input / finalkey)
var decrypted = String.fromCharCode(inputdiv)
alert(decrypted)
}
</script>
<script>
function keycheck(form) {
if (finalkey != null) {
null
} else {
alert("Please enter a key. This will determine how your encryptions and decryptions are made.")
}
}
</script>
<center>
<br> <br>
<br> <br>
<form name="keyinput">
<input type="text" id="key" name="key">
<br>
<input type="button" name="keysub" id="keysub" value="Submit Key" onclick="submitkey(this.form)">
</form>
<p id="asciikeyout"></p>
<p id="key2"></p>
<br> <br>
<br> <br>
<br> <br>
<form name="field">
<input type="button" name="decryptbutton" onclick="dec(this.form)" value="Decrypt">
<br>
<textarea id="input" rows="4" cols="50" onkeyup="getascii(this.form)" onkeydown="keycheck(this.form)"></textarea>
<br>
<br>
<textarea id="output" rows="20" cols="70" fontsize="18px" readonly></textarea>
</form>
<p id="res2"></p>
</center>
</body>
</html>

Javascript : How to check multiple empty values

I have four input elements in my form. I don't have submit button in my form. I want to check all the values and if all the values are not empty then I want to post that all values to php page by using ajax.
This is my form input elements.
<form method="post" action="getAllDteails.php" name="dashboard">
Manager Name<input type="text" id="managername" onchange="getDetails(this.value)" name="managername"/>
Project Name<input type="text" id="projectname" onchange="getDetails(this.value)" name="projectname"/>
Task Name<input type="text" id="taskname" onchange="getDetails(this.value)" name="taskname"/>
Completion Date<input type="date" id="date" onchange="getDetails(this.value)" name="date"/>
<div id="cool"></div>
</form>
This is my script.
function getDetails()
{
var mname = document.getElementById('managername').value;
var pname = document.getElementById('projectname').value;
var tname = document.getElementById('taskname').value;
var cdate = document.getElementById('date').value;
//alert(mname);
if(mname!==null&&pname!==null&&tname!==null&&cdate!==null)
{
alert("true");
var jsonobj = {"mname" : mname, "pname" : pname, "tname" : tname, "cdate" : cdate};
var js = JSON.stringify(jsonobj);
alert(js);
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert(js);
document.getElementById("cool").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","getAllDetails.php?js="+js,true);
xmlhttp.send();
}
}
Just am getting all the values and assigning to four variables. If the four variables are not null then I want to assign all that in single object. But the problem is every time it is coming inside the condition and showing alert.
At fourth time also it is showing the alert. But the values are not going to php page. I'am a beginner Please guide me if I approached in a wrong way.
1.Change Html Code to new code
<form method="post" action="getAllDteails.php" name="dashboard">
Manager Name<input type="text" id="managername" name="managername" class="v1"/>
Project Name<input type="text" id="projectname" name="projectname" class="v1"/>
Task Name<input type="text" id="taskname" name="taskname" class="v1"/>
Completion Date<input type="date" id="date" name="date" class="v1"/>
<input id="Button1" type="button" value="button" onclick="return checkData();" />
</form>
2.Change Script Code to new script code (for checking multipe value)
function checkData() {
var _v = document.getElementsByClassName("v1"); // get all field
var _empty = false; // default has false;
var _jsParm = '';
for (var i = 0; i < _v.length; i++) {
if (_v[i].value == '') {
_empty = true; // if value of null or empty; *
break;
}
_jsParm += _v[i].id + ':\'' + _v[i].value + '\',';
}
//* if any field is null , show alert
if (_empty == true) {
alert('Error!!!!! \r\n Please enter data in all field.');
return false;
}
alert('OK! all field has data.' + '\r\n' + _jsParm)
_jsParm = _jsParm.substr(0, _jsParm.length - 1);
var jsonobj = '{' + _jsParm + '}';
var js = JSON.stringify(jsonobj);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(js);
document.getElementById("cool").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "getAllDetails.php?js=" + js, true);
xmlhttp.send();
}
3.Save
4.Enjoy Now!

Categories

Resources