Javascript : How to check multiple empty values - javascript

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!

Related

How to store javascript values into mysql database?

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);">

Checking form fields with AJAX and PHP

I am trying to write a code that will check in a php file if username/mail has already been registered. The following code doesn't work because in check_fields() when check_field() is fired for both files the return is sent immediately, without waiting for the asynchronous query to finish. I don't want to use JQuery so I thought about doing the following :
a function is linked to the onsubmit of the form
a AJAX call is made to the server to launch a php file
this file analyses the input and return a error response if it needs to : "field is empty", "email already used", "incorrect email adress", ect...
when the AJAX call is finished a function (or callback) will be fired. This function will check the .textContent of the <span id="username_err"></> and <span id="mail_err"></> to see if the php has noticed to errors. If it's not blank (there's a problem in the input) the function return false to the initial function.
the return value is sent back to the form
if true, form is submitted to server...
That's what I would like to try out, is this ok ? Is there a way to do this without a promise ?
[Original code]
<html>
<body>
<form style="text-align:center" action="mama.php" method="post" onsubmit="return check()">
<div class="username">
<span id="label_username">Username :</span>
<input type="text" id="username" name="username">
<p id="username_err"></p>
</div><br />
<div class="mail">
<span id="label_mail">Mail :</span>
<input type="text" id="mail" name="mail"></input>
<p id="mail_err"></p>
</div><br />
<input type="submit" id="envoyer" value="Envoyer" />
</form>
</body>
<script>
function check() {
return check_fields(['username', 'mail']);
}
function check_fields(items) {
var check = true;
for (i = 0; i < items.length; i++) {
check_field(items[i]);
};
for (i = 0; i < items.length; i++) {
var value = document.getElementById(items[i] + '_err').textContent;
if (value != '') {
check = false
}
};
return check
}
function check_field(id) {
var value = document.getElementById(id).value;
ajax_php(id, value, 'check_field.php', function(returned_value) {
document.getElementById(id + '_err').innerHTML = returned_value;
});
}
function ajax_php(id, value, file, fn) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
fn(xmlhttp.responseText);
}
};
xmlhttp.open('GET', file + '?' + id + '=' + value, true);
xmlhttp.send();
}
</script>
</html>
[Possible solution]
<html>
<body>
<form style="text-align:center" action="mama.php" method="post" onsubmit="check(this)">
<div class="username">
<span id="label_username">Username :</span>
<input type="text" id="username" name="username">
<p id="username_err"></p>
</div><br />
<div class="mail">
<span id="label_mail">Mail :</span>
<input type="text" id="mail" name="mail"></input>
<p id="mail_err"></p>
</div><br />
<input type="submit" id="envoyer" value="Envoyer" />
</form>
</body>
<script>
function check_fields(form, items) {
var success = true;
function check_field(i) {
var id = items[i];
var value = document.getElementById(id).value;
ajax_php(id, value, 'check_field.php', function(returned_value) {
document.getElmentById(id + '_err').textContent = returned_value;
if (returned_value != '') {
success = false;
}
if (++i < items.length) {
check_field(i); // Check the next field
} else if (success) { // reached the last field with no errors
form.submit();
}
});
}
check_field(0);
}
function check(form) {
check_fields(form, ['username', 'mail']);
return false; // prevent form submission
}
function ajax_php(id, value, file, fn) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
fn(xmlhttp.responseText);
};
};
xmlhttp.open('GET', file + '?' + id + '=' + value, true);
xmlhttp.send();
};
</script>
</html>
Chain the AJAX calls for each field. The callback for field i submits the AJAX call to check field i+1, and so on. The last callback submits the form if all were successful.
function check_fields(form, items) {
var success = true;
function check_field(i) {
var id = items[i];
var value = document.getElementById(id).value;
ajax_php(id, value, 'check_field.php', function(returned_value) {
document.getElementById(id + '_err').textContent = returned_value;
if (returned_value != '') {
success = false;
}
if (++i < items.length) {
check_field(i); // Check the next field
} else if (success) { // reached the last field with no errors
form.submit();
}
});
}
check_field(0);
}
function check(form) {
check_fields(form, ['username', 'mail']);
return false; // prevent form submission
}
The form should contain:
onsubmit="return check(this)"

Javascript/ajax is passing all form textfield values to the php but not the last textfield value

This is my html with form and javascript/ajax function. All the textfield values are passed to the test.php. When I do so, if i enter the first three textfields then test.php will successfully display the form values. But on the other hand, if I fill all the four textfield and send then nothing will happen. Since, I am new in the programming, i could not figure this issue out. I would be thankful for the solution of this issue.
#form.html
<html>
<SCRIPT language="javaScript">
function sendData(){
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXobject ('Mircosoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById('message').innerHTML = xmlhttp.responseText;
}
}
var i=0;
var arr = new Array();
while ((document.getElementById(i).value)) {
if ((document.getElementById(i).value)!=""){
var activity = document.getElementById(i).value;
arr[i] = activity;
}
i++;
}
var params = 'activity='+JSON.stringify(arr);
xmlhttp.open('POST','test.php', true);
xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlhttp.send(params);
document.getElementById("message").innerHTML = "Sending...";
}
</script>
<form action="#" method="POST">
<tr>Name1:<td> <input type="text" id="0"/> </td></tr><br>
<tr>Name2:<td> <input type="text" id="1"/> </td></tr><br>
<tr>Name3:<td> <input type="text" id="2"/> </td></tr><br>
<tr>Name4:<td> <input type="text" id="3"/> </td></tr><br>
<input type="button" value="Send" onclick="sendData()";/>
</form>
<div id="message">
</div>
</html>
This is the test.php file where the form value will be displayed.
#test.php
<?php
$activity = $_POST['activity'];
$activity = json_decode($activity);
if (is_array($activity)){
foreach ($activity as $value){
echo $value."<br>";
}
}
else {
echo "error";
}
?>
The issue is with
while ((document.getElementById(i).value)) {
It works just fine until i === 4, then getElementById returns null, and null.value is an error, so the whole thing errors out.
Using a while loop for this doesn't really seem like a good idea, but something like this should at least work
while (document.getElementById(i)) {
if ((document.getElementById(i).value) != "") {
arr[i] = document.getElementById(i).value;
}
i++;
}
Getting the elements by class, tagname or something else other than numeric ID's seems better
var arr = new Array();
var elems = document.querySelectorAll('.inputs'); // class
for ( var i=0; i<elems.length; i++ ) {
arr.push(elems[i].value)
}

Sending parameters with ajax not working

I'm trying to send some variables using ajax to a php page and then displaying them in a div but it isn't working.
Html code :
<div id="center">
<form>
<input type="text" id="toSearch" class="inputText" title="Search for ...">
<select name="thelist1" id="ecoElem" class="comboBox">
<option>-- Ecosystem Element --</option>
</select>
<select name="thelist2" id="ecoActor" class="comboBox">
<option>-- Ecosystem Actor --</option>
</select>
<input type="button" value="Search" id="searchButton" onclick="loadData();">
</form>
</div>
<div id="resBox">
</div>
The loadData function :
function loadData(){
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else{
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
searchT = document.getElementById('toSearch').value;
ecoElem = document.getElementById('ecoElem').value;
ecoActor = document.getElementById('ecoActor').value;
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById('resBox').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST","databaseRead.php",true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send("text=" + searchT + "&elem=" + ecoElem + "&actor=" + ecoActor);}
and finally the php page :
<?php
$searchT = $_POST['text'];
$ecoElem = $_POST['elem'];
$ecoActor = $_POST['actor'];
echo $searchT;
?>
That's it , I've been working on this for a few hours but still can't figure it out.
Try changing the button so that the onclick return false (in case that is submitting the form)...
<input type="button" value="Search" id="searchButton" onclick="loadData();return false;">
Also, you might want to URL encode the values from the textbox, otherwise somebody entering a = or a & will mess it all up...
xmlhttp.send("text=" + encodeURIComponent(searchT) + "&elem=" + + encodeURIComponent(ecoElem) + "&actor=" + + encodeURIComponent(ecoActor));}
You could also use JQuery.
function loadData(){
var searchT = $('#toSearch').val();
var toSearch = $('#ecoActor ').val();
var ecoActor = $('#ecoActor').val();
$.post("databaseRead.php"),{ text:searchT, elem:toSearch, actor:ecoActor },
function(data){
$('#resBox').html(data);
});
}

Javascript two submit buttons in one form almost complete

I have a form with two submit buttons with onClick events attached. The form action is a paypal form.
If make a payment button is pressed the form is emailed and then redirects to paypal for payment.
If the invoice button is pressed an email is sent with the form details but the default action of redirecting to PayPal is stopped.
It all seems to work fine but when the invoice buttin is pressed it still redirects to paypal.
If the invoice button is pressed i want it to send the email but then stop and not continue on with the form action.
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" id="paymentform" name="paymentform">
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="currency_code" value="GBP">
<fieldset id="your_details" class="">
<legend>Your Details</legend>
<ol>
<li><label for="your_name">Your Name</label><input type="text" name="your_name" value="" id="your_name" class="large "></li>
<li><label for="your_position">Your Position</label><input type="text" name="your_position" value="" id="your_position" class="large"></li>
<li><label for="your_company">Your Company</label><input type="text" name="your_company" value="" id="your_company" class="large "></li>
<li><label for="your_telephone">Your Telephone</label><input type="text" name="your_telephone" value="" id="your_telephone" class="medium "></li>
<li><label for="your_mobile">Your Mobile</label><input type="text" name="your_mobile" value="" id="your_mobile" class="medium"></li>
</ol>
</fieldset>
<input type="submit" value="Pay by Credit Card →" id="cc" onclick="return email_me(document.paymentform);" class="submit_button">
<input type="submit" value="Pay by Invoice →" id="invoice" class="submit_button" onclick="return email_me(document.paymentform,true);">
var xmlHttp;
var formname;
var invoiceonly_var
function email_me(Form,invoiceonly)
{
formname = Form.name;
var params = "";
var i;
var Element;
var type;
var name;
var fieldvalue;
var optional;
var BadFields = "";
var Title;
var Titles = new Array();
Titles['item_name'] = "Course Title";
var outMessage = "";
invoiceonly_var = invoiceonly;
//alert(formname);
//alert(Form.length);
var Optional = new Array();
// optional fields
Optional['your_position'] = true;
Optional['your_mobile'] = true;
for(i = 0; i < Form.length; i++)
{
Element = Form.elements[i];
type = Element.type;
name = Element.name;
//alert("name:"+name+" type:"+type);
if(type == "text")
{
fieldvalue = Element.value;
params = params + name + "=" + fieldvalue + "&";
optional = Optional[name];
if ( (fieldvalue == '' || fieldvalue == name ) && typeof(optional) == "undefined")
{
Title = getTitle(name,Titles);
BadFields += "- " + Title + "\n";
}
//alert(params);
}
if(type == "textarea")
{
fieldvalue = Element.value;
params = params + name + "=" + fieldvalue + "&";
optional = Optional[name];
if ( (fieldvalue == '' || fieldvalue == name ) && typeof(optional) == "undefined")
{
Title = getTitle(name,Titles);
BadFields += "- " + Title + "\n";
}
//alert(params);
}
}
if(BadFields)
{
outMessage = "We are unable to proceed as the following \n";
outMessage += "required fields have not been completed:\n\n";
outMessage += BadFields;
alert(outMessage);
return false;
}
//alert(params);
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
url="/payment/ajax_email_me.php?";
if (invoiceonly_var == true)
{
params = params + "Payment_Method=Invoice";
}
else
{
params = params + "Payment_Method=PayPal&";
}
url=url+params;
//alert(url);
xmlHttp.onreadystatechange = Finished;
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
return true;
}
function Finished()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
//document.getElementById('search').innerHTML = xmlHttp.responseText;
var response = xmlHttp.responseText;
//alert(response);
if (invoiceonly_var == true)
{
alert("Thank you. Your message has been sent.");
}
else
{
document.paymentform.submit();
}
document.body.innerHTML = document.body.innerHTML + "<span></span>";
}
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
// alert("Mozilla");
}
catch (e)
{
//Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
// alert("IE");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
// alert("IEError");
}
}
return xmlHttp;
}
function selectval(Sel)
{
return Sel.options[Sel.selectedIndex].value;
}
function getTitle(name,Titles)
{
Title = Titles[name];
if (typeof(Title) == "undefined")
{
Title = name;
Title = Title.replace(/_/g," ");
}
return Title;
}
First of all, your code could be greatly simplified with the use of jQuery to abstract away much of the AJAX logic here.
Secondly, you have return true at the bottom of your email_me function - try changing this to:
return !invoiceonly;
Returning false from this function will prevent the form from submitting. When the invoice button is clicked (and the invoiceonly parameter is set to true) you do not want the form to submit, so the above logic will make the function return false.
Usually I would suggest adding ";return false" after the Javascript you want to run, but since you're already returning a value, I'm not sure that will work. Give it a shot, though, and if it doesn't work, can I ask what the return value is doing?
Something like this:
<input type="submit" value="Pay by Invoice →" id="invoice" class="submit_button" onclick="return email_me(document.paymentform,true);return false">
Did you try adding "return false" to the end of the onclick event which you don't want to submit?
Or you can change the type to "button" from "submit" - that might do the trick.

Categories

Resources