Friday, December 9, 2011

FORM validation with jquery.ajax

When <FORM> validation meet the JQUERY.AJAX

Below are the basic <FORM> with validation before the form submitted.

1  <script>
2    function validateform() {
3       $.ajax({
4           type: "POST",
5           url: "/country/checkcountry",
6           data: "code="+countrycode+"&name="+countryname,
7           dataType: 'json',
8           success: function (data, status)  {
9               if (data.result != 'OK') {
10                 console.log('check ok'); 
11                 return false
12              } else {  
13                 console.log('check not ok'); 
14                 return true
15              }
16          },
17          error: function (data, status) {
18              console.log('check error') 
19              return false
20          }
21      });         
22      console.log('should never show');
24      return false; //For testing purpose, it should be return true
25   }
26 </script>
28 <FORM action="/country/addcountry" method="post" onsubmit="return validateform()">
29     ..........................
30 </FORM>

At the first glance, the java script seem logically fine. Actually, there are TWO major issue in that java script!

1. ASYNC issue
If we really make above code run-able, no matter what result we get from the ajax call, we will still  get the "should never show" message at line 22 then follow by the console message from the ajax stub (10,13 or 18).

By default, jquery ajax is a asynchronous process. This means once the ajax triggered, browser will not wait until it complete but rather continue with the next task. For our case is the console.log at line 22.

This is not the result we want, specially a sequential validation activity. I order to solve this, we need to add a parameter to the ajax as shown below.
asycn: false,

2. Return operation in jquery ajax
After insert the async parameter to ajax, then let's try again. aiks... still cannot get the expected result, although by now the sequence of the log is correct. By now, we should get the console message  from the ajax stub (10,13 or 18) first then follow by message at line 22. But the function should not reach line 22, it should return at line 11, 14 or 19.

The catch is, jquery ajax execute their operation at another thread and not in the same scope with validateform function. The return operation in ajax only quit from it's own thread but not the function. In order to solve this, declare a boolean variable at the scope of validateform function then assigned the status and perform necessary action after the ajax task. See below code for complete solution.

1  <script>
2    function validateform() {
3       var validateResult = true;
5       $.ajax({
6           type: "POST",
7           url: "/country/checkcountry",
8           data: "code="+countrycode+"&name="+countryname,
9           dataType: 'json',
10          success: function (data, status)  {
11              if (data.result != 'OK') {
12                 console.log('check ok'); 
13                 validateResult=false;
14              } else {  
15                 console.log('check not ok'); 
16                 validateResult=true;
17              }
18          },
19          error: function (data, status) {
20              console.log('check error') 
21              validateResult=false
22          }
23      });         
25      return validateResult;
26   }
29 </script>
31 <FORM action="/country/addcountry" method="post" onsubmit="return validateform()">
32     ..........................
33 </FORM>

Ajax task may take some time to complete, if you using it at form validation specially submit validation, is recommended to show some indication to user to inform their action is under process.

No comments:

Post a Comment