AJAX Form Validation

a web form is a prime example of an application that ajax can enhance its responsiveness and usability. at a bare minimum, a form should do the following:

  • check for empty fields
  • check for valid characters
  • check for duplicates

if everything is ‘ok’, submit the form.

faced with a multi-field form, it would be great if our inputs were validated on the fly. that way, you could correct any errors before the form is submitted.

xmlhttprequest object = ajax

all data is stored in xmlhttprequest object which is transferred between the browser and server. before any data can be handled we need to create an instance of this object.

function ajaxinit() {
	// xmlhttprequest object
	var ajaxrequest = false;

	try {
		// supports ie7+, firefox, chrome, opera, safari
		ajaxrequest = new xmlhttprequest();

	} catch (e) {

		try {
			// supports ie6, ie5
			ajaxrequest = new activexobject("msxml2.xmlhttp");

		} catch (e) {
			// browser doesn't support xmlhttprequest objects
			ajaxrequest = false;
			alert("your browser does not support the ajax methods!");
		}
	}
        return ajaxrequest
}

this function checks your browser for xmlhttprequest support. if the browser doesn’t support the object, the function returns false and throws up an error message rendering ajax capabilities useless.

get form values

to pass data to our server, we will have to construct a function that creates the query sent to the server.

// get form values
function checkfields(){
	document.getelementbyid('user-form').onkeyup = function(){
		var params = '';
		var username = document.getelementbyid("name");
		var action = "action=checkusername";

		params += username.name;
		params += '=';
		params += username.value;
		params += "&";
		params += action;

		return senddata(params);
	}
}

the onkeyup event triggers the function and when complete, the variable params holds a string of names and values taken from the form. this data will then be passed to the senddata function.

passing data to the server

three critical components involved in this process include:

  • onreadystatechange
  • open
  • send

without those components functioning, no data could be passed to the server.

// send form values to the server
function senddata(params){
	var request = ajaxinit();
	if(request){
		request.onreadystatechange = function(){
			handledata(request);
		}
		request.open("post", "register.php", true);
		request.setrequestheader("content-type", "application/x-www-form-urlencoded");
		request.send(params);
		return true;
	} else {
		return false;
	}
}

after our onreadystatechange function fires and sends a request to the server, we have to deal with handling the server’s response.

processing the server’s response

the evalstatement executes the json formatted data sent from the server. all json values are now accessible as properties of the variable resp.

function handledata(request){
	if(request.readystate == 4 && request.status == 200){
		var resp = eval('('+request.responsetext+')');
		var result = resp.ok;
		var msg = resp.msg;
		var placeholder = document.getelementbyid("validation");

		if(!result){
			placeholder.innerhtml = msg;
		} else {
			placeholder.innerhtml = msg;
		}

		return true
	} else {
		return false;
	}
}

the innerhtmlproperty then updates the html element with the data stored in the variable.

load the script

finally, to extract the user’s input from the form field, the checkfieldsfunction needs to be loaded into the document when requested from the server.

window.onload = checkfields();

resources

check out the demo to see this script in action or download the files to use for yourself.

Leave a Reply

Your email address will not be published. Required fields are marked *