I want to know if this would be considered a proper way to validate a form or if there is an easier way that I'm not aware of.
I think I was reading somewhere that you are not supposed to use isNaN
with AJAX but this seems to work for me. Can I just leave as is since it works or is there a better structure/system that I should be following?
function AjaxPost () {
// Declaring my variables
var xmlhttp;
var url = "weight_p.php";
var age = document.getElementById("age").value;
var height_ft = document.getElementById("height_ft").value;
var height_in = document.getElementById("height_in").value;
var weight = document.getElementById("weight").value;
var gender = document.getElementById("gender").value;
var activity = document.getElementById("activity").value;
// Validate all values entered
if (age == "" || isNaN(age)) {
alert("Please insert age, must be numerical!");
return false;
}
if (height_ft == "" || height_in == "" || isNaN(height_ft) || isNaN(height_in)) {
alert("Please insert height, must be numerical!");
return false;
}
if (weight == "" || isNaN(weight)) {
alert("Please enter weight, must be numerical!");
return false;
}
if (gender == "") {
alert("Please select gender");
return false;
}
if (activity == "") {
alert("Please select activity level!");
return false;
}
// These are all the values we are sending
var info = "age="+age+"&height_ft="+height_ft+"&height_in="+height_in+"&weight="+weight+"&gender="+gender+"&activity="+activity;
// Check to see if browser is compatable
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// IE6, IE5, and older browsers
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var return_data = xmlhttp.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
xmlhttp.send(info);
document.getElementById("status").innerHTML = "Processing....";
}