Sunday, January 20, 2013

Dead simple Ajax form validation

It took a while for me to sift through all the examples to simplify the concept down to what I needed.  I need to validate chess moves based on the current chess board before the submission of the move (or else people on AWS Turk will submit lots of badly formed moves). "validate_move.py" is a Python CGI program that reads the QUERY_STRING to get the move and then sends back a "t" if the move is good or "f" if it is false.

<html> <head> <script> var OK2Submit = false; function validateMove() { OK2Submit = false; document.getElementById("moveDiv").innerHTML="<i>Validating move...</i>"; var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { var moveGood=xmlhttp.responseText; if(moveGood.charAt(0)=="t"){ OK2Submit=true; document.getElementById("moveDiv").innerHTML='<i>That is a valid move, you may submit it</i><br><input type="submit" value="Submit">'; } else { document.getElementById("moveDiv").innerHTML="<i>Not a valid move!</i>"; } } } xmlhttp.open("GET","validate_move.py?"+document.forms["myForm"]["move"].value,true); xmlhttp.send(); return false; } </script> </head> <body> <form name="myForm" action="action.py" onsubmit="return OK2Submit" method="post"> Enter Move: <input type="text" name="move" onchange="validateMove();"> <br> <div id="moveDiv"></div> <br> </form> </body> </html>

No comments: