Correct AJAX form validation?

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...."; }

--------------Solutions-------------

For a problem like this, I would try to find a way to use loops to make it easier to add and remove things from your form. Right now, if you want to add something, you have to go through and edit almost every part of your code.

I find that the easiest way to get these things into loops would be to create objects for each form element:

function FormElement(name, isNumber) {
this.name = name;
this.val = document.getElementById(name);
this.isNumber = isNumber;
}

Then, the top of your function would look like this:

var age = new FormElement("age", true);

...

var gender = new FormElement("gender", false);

And, to make iterating easier, let's stick these in an array:

var formElements = [age, height_ft, height_in, weight, gender, activity];

Now, all we have to do is iterate through them and check their properties:

for(var i = 0; i < formElements.length; i++) {
if(formElements[i].val == "" || (formElements[i].isNumber && isNaN(formElements[i].val)) {
var err = "Please ";
if(formElements[i].isNumber) {
err += "insert " + formElements[i].name + ", must be numerical.";
} else {
err += "select " + formElements[i].name + ".";
}
alert(err);
}
}

Note: I noticed a pattern in your code; for every element that required numerical input, it's error message used the verb "insert", and for every elemnt that required string/select input, it's error message used the verb "select". I used this pattern to auto-generate an error message.

Now, for setting up the info variable, all we have to do is iterate through the element array again but this time, as we are iterating, concatenate the name property of each object into the string, an '=', and then the value delimited by a &:

for(i = 0; i < formElements.length; i++) {
info += formElements[i].name + "=" + formElements[i].val;
if(i != formElements.length - 1) { // so we don't add a '&' to the end of the string
info += "&";
}
}

Putting that all together, your code would look like this:

function AjaxPost () {

var xmlhttp;
var url = "weight_p.php";

var age = new FormElement("age", true);
var height_ft = new FormElement("height_ft", true);
var height_in = new FormElement("height_in", true);
var weight = new FormElement("weight", true);
var gender = new FormElement("gender", false);
var activity = new FormElement("acitivity", false);

// Validate all values entered
for(var i = 0; i < formElements.length; i++) {
if(formElements[i].val == "" || (formElements[i].isNumber && isNaN(formElements[i].val)) {
var err = "Please ";
if(formElements[i].isNumber) { // use verb "insert"
err += "insert " + formElements[i].name + ", must be numerical.";
} else { // use verb "select"
err += "select " + formElements[i].name + ".";
}
alert(err);
}
}

// These are all the values we are sending
for(i = 0; i < formElements.length; i++) {
info += formElements[i].name + "=" + formElements[i].val;
if(i != formElements.length - 1) { // so we don't add a '&' to the end of the string
info += "&";
}
}

... the rest is the same ...
}

Now, all you have to do when you add a new form element is create a new FormElement object and add it to the array.

If you encounter any bugs with this code, notify me.

Category:javascript Time:2018-12-05 Views:1

Related post

  • rails jquery ajax form validation 2009-05-04

    I'm looking to do some ajax form validation with jquery. Everything is in place and I can return my errors in a json object that looks something like this: errors => { "first_name": "cannot be blank", "password": "cannot be blank", "last_name": "c

  • Ajax form validation in codeigniter 2011-04-03

    hellp guys, I've been working on ajax recently, and I have a problem in using it with codeigniter form validation library. I used the example that tool generate in the function http://formtorch.geekhut.org/. Now, ajax works perfectly and return data

  • JQuery / Ajax Form Validation - How to not submit form unless form validates and ajax validates 2011-11-10

    I am using this form validator (http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/) and am having issues getting it to properly validate both the regular fields and 2 fields I have using AJAX validation

  • Ajax form validation 2009-05-01

    I have created an form validation using ajax/php. Each text box is validated using a different file e.g. username_ajax.php. Once the information has been checked to be ok it is then echoed on screen ("Username ok"). I cannot figure out how to allow t

  • Ajax Form Validation Problem 2010-01-27

    I've got my form validation almost working but I can't seem to figure this last problem out. I'm trying to send back error messages and position them in their own div next to their relevant form fields. I've got an error message coming back in its ow

  • Can't seem to get Prototype AJAX form validation to work in conjunction with Codeigniter 2010-06-16

    Is there some kind of trick involved? Here's how I would envision it working: User tries submitting the form Event.observe captures this and sends an AJAX request to a special validation URL (PHP using Codeigniter) If no errors were returned, continu

  • jquery ajax form validation on submission then continue on to form submission 2011-03-02

    Here is what I'm trying to do, Capture my form submission post it to my ajax processing for form validation (without a page reload obviously) then if the ajax server side doesn't return an array of errors (data in the code below) go ahead with the ac

  • To ajax or not to ajax form validation? 2011-09-05

    I see two common ways to implement form validation: Send form by ajax, retrieve success flag and in the case of success redirect somewhere Classical Post-Redirect-Get What is the prefered way? According to my observation, redirect is slower in the ca

  • Ajax Form Validation, JSON code 2011-05-30

    I have 3 fields in my ajax registration form. Each of them under success has: success: function (j) { if (j.ok){ $(validateEmail.html(j.msg)).attr("id","accept").appendTo($('#loginform') ); } else { $(validateEmail.html(j.msg)).attr("id","invalid").a

  • ASP.Net C# Ajax Form Validation and Submit button status 2012-04-13

    I have a quite complicated form, and i would like to validate the form before it is submitted in some nice looking ajax way. As part of this i would also like to only enable the forms submit button once the form is correctly filled in. I'm using C#/a

  • What is the proper way to do multi-parameter AJAX form validation with jQuery and ASP.NET MVC? 2009-10-23

    I have a registration form for a website that needs to check if an email address already exists for a given company id. When the user tabs or clicks out of the email field (blur event), I want jQuery to go off and do an AJAX request so I can then war

  • Rails: Ajax form validations with error_message_on 2010-01-21

    I've been trying to get get some ajax validations going in my form and have been running into a bit of trouble I have code like this in my form: <% form_for @user, :html => { :id => 'user_form', :multipart => true } do |f| %> <%= f.

  • Post extra string through ajax form validation script 2011-03-31

    I am trying to pass a custom variable and value through ajax when the form submission event starts, they have this option when you validate field on blur but when the form is submitted I don't see how to add custom variable to this. This what they ha

  • Grails JQuery Ajax Form Validation 2011-10-10

    I have a modal dialog where I load a form from a gsp and I am struggling to find the right solution for an ajax based form with JSON validation incl. success message like a flash scope message: $('#calendar_form').live('click', function () { $.modal(

  • ajax form validation with PHP 2012-01-15

    I am using PHP Zend framework and jQuery ajax to submit and validate a form using json data format. The PHP works great, the ajax works great too. The only problem is that if the form has more than one invalid input (e.g name and email are both inval

  • jQuery+ajax form validation and submission with a twist 2012-04-03

    I've cobbled together a jQuery function to validate email and submit the form using ajax. So far the validation function works okay (gives me error messages) But if the user enters valid email, I want my ajax function to run (it's seutp already). Rig

  • Ajax form validation refuses to work 2011-03-27

    I'm trying to validate a form using ajax and it just won't work for me, so before I mess the thing up completely I thought I'd ask for some help before continuing, thanks in advance to anyone who can help :) http://pastebin.com/0t53EE0g <- access.

  • mvc3 - ajax form submit and server side validation 2012-01-11

    I am sure this has been asked already, but I have been trying all the solutions given, but none of the given solution is solving my problem. Probably, I am not implementing it right. I am using MVC3, razor, jQuery. I have a new user registration form

  • Ajax form submission with jquery.validate.js and jquery.form.js? 2012-04-15

    I am trying to submit my html form data to a servlet by mixing two different javascript codes together one is: <script type="text/javascript"> $(document).ready(function() { $("#form1").validate({ rules: { name: "required", email: { required: t

Copyright (C) pcaskme.com, All Rights Reserved.

processed in 1.542 (s). 15 q(s)