Using  Coldfusion  in built AJAX  & JSON  Functions to submit and validate a form

AID: 2024
  • Status: Published

4200 points

This article  is about submitting  form through  ColdFusion.Ajax.submitForm to the action page and send a response back in JSON format which later can be decoded using ColdFusion.JSON.decode. By this way you can avoid the usual page refresh for submitting the forms and also sending response back in the best way which is JSON (JavaScript Object Notation).

    Form

A simple user form which gives the option of entering Name and Email.

 
<CFAJAXIMPORT />
<cfform name="frm" method="post" id="frm"> 
Name:
 <cfinput id="Name" name="Name"   /> 
 <div id="NameError"></div> 
 </div>  
Email Address :
 <cfinput id="emailAddress" name="emailAddress"   /> 
 <div id="emailAddressError"></div> 
 </div> 
 
 <div><cfinput name="submit" type="button" value="submit" onclick="Formsubmition();"></div> 
</cfform> 

<script>
function Formsubmition() { 
document.getElementById("NameError").innerHTML = ''; 
document.getElementById("emailAddressError").innerHTML = ''; 
ColdFusion.Ajax.submitForm('frm','action.cfm', responsecallback, errorHandler);
}
function responsecallback (response){ 
     var errors = ColdFusion.JSON.decode(response); 
     var errorexist = false; 
      
     for(i in errors){ 
         document.getElementById(i+"Error").innerHTML = errors[i]; 
          errorexist = true; 
     } 
   
     if(! errorexist){ 
         alert('Data Inserted');
     } 
} 
 function errorHandler(id, message) {
	
	   alert("Error while inserting\n Error code: "+id+"\n Message: "+message); 
		
	
	} 
</script>

                                    
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:

Select allOpen in new window




We have a simple form frm with an option to enter name and email.
We have simple div below each form input field with a unique respective ids. we use these divs  to print errors after validating the form.
On click of submit button js function  Formsubmition is triggered which submits  the form using ColdFusion.Ajax.submitForm.

ColdFusion.Ajax.submitForm  -- http://livedocs.adobe.com/coldfusion/8/JavaScriptFcns_03.html
       ColdFusion.Ajax.submitForm function to submit form contents to a CFML page or to a CFC  without refreshing the page.

ColdFusion.Ajax.submitForm('frm','action.cfm', responsecallback, errorHandler);
           In our page ColdFusion.Ajax.submitForm method takes the values of all of the items in the form frm , and posts them to the file 'action.cfm. When we get back a response, the responsecallback function is called, and should there be any errors, the errorHandler method is executed.

One important thing  ColdFusion.Ajax.submitForm function does not support uploading a file attachment to the form.

Action

A action page which validates all inputted data and returns the errors in json format is there are any errors else insert the data in to DB.

action.cfm  file

 
<cfsetting enablecfoutputonly="true" /> 
<cfset errors = StructNew() />  
<cfif form.Name EQ ""> 
 <cfset errors["Name"] = "You must enter a first name." /> 
</cfif>  
<cfif NOT isValid("email", form.emailAddress)> 
 <cfset errors["emailAddress"]= "You must enter a valid email address" /> 
</cfif>  

<cfif structIsEmpty(errors)> 
     <!--- insert in to db --->
<cfelse> 
 <cfoutput><cfoutput>#serializeJSON(errors)#</cfoutput></cfoutput> 
</cfif> 
<cfsetting enablecfoutputonly="false" />

                                    
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:

Select allOpen in new window



A coldfusion structure  named errors is created  which will hold all the validation errors with key names equal to the div ids given in the form page under each input field. This actually helps in populating data in to the corresponding divs.

If the Errors structure is empty after all validations we insert  in to Database .
IF the Error Structure is not empty then we serialize the Error structure to JSON string using
serializeJSON (serialize a ColdFusion object into a JSON string.)
http://livedocs.adobe.com/coldfusion/8/htmldocs/help.html?content=ajaxdata_09.html

As we are wrapping the Json string in <cfoutput> </cfoutput> tags  the JSON string will be sent back in response for the Coldfsuion.ajax.Submitform call if there are any errors.
Responsecallback function takes one parameter which is the  response sent back by server.

 
function responsecallback(response){ 
     var errors = ColdFusion.JSON.decode(response); 
     var errorexist = false; 
      
     for(i in errors){ 
         document.getElementById(i+"Error").innerHTML = errors[i]; 
          errorexist = true; 
     } 
   
     if(! errorexist){ 
         alert('Data Inserted');
     } 
}

                                    
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:

Select allOpen in new window



The returned response in JSON so we decode to JavaScript object using ColdFusion.JSON.encode(accepts a JavaScript object, and returns a JSON string).
We loop over through elements of this JavaScript object  and set the content of corresponding Div with Error message and set the variable errorexist to true which is initially set to false.


We can use this variable to display or do whatever we want  like we are alerting 'Data Inserted' in our example.


Summary

These is an simple example which explains the use of coldfusion.ajax.submitform and JSON functions which are one of the best additions to built in functions in Coldfusion 8.


There are  many Inbuilt  Ajax and JSON functions  in Coldfusion.  Below URL explains some of them  
http://livedocs.adobe.com/coldfusion/8/htmldocs/help.html?content=JavaScriptFcns_02.html
Asked On
2009-11-27 at 02:07:13ID2024
Tags

Coldfusion

Topic

Cold Fusion Markup Language

Views
3044

Comments

Add your Comment

Please Sign up or Log in to comment on this article.

Join Experts Exchange Today

Gain Access to all our Tech Resources

Get personalized answers

Ask unlimited questions

Access Proven Solutions

Search 3.2 million solutions

Read In-Depth How-To Guides

1000+ articles, demos, & tips

Watch Step by Step Tutorials

Learn direct from top tech pros

And Much More!

Your complete tech resource

See Plans and Pricing

30-day free trial. Register in 60 seconds.

Loading Advertisement...

Top ColdFusion Language Experts

  1. _agx_

    268,859

    Guru

    2,000 points yesterday

    Profile
    Rank: Genius
  2. gdemaria

    184,144

    Guru

    1,800 points yesterday

    Profile
    Rank: Genius
  3. SidFishes

    87,866

    Master

    2,000 points yesterday

    Profile
    Rank: Genius
  4. myselfrandhawa

    58,872

    Master

    0 points yesterday

    Profile
    Rank: Guru
  5. dgrafx

    36,068

    0 points yesterday

    Profile
    Rank: Sage
  6. pravinasar

    26,318

    0 points yesterday

    Profile
    Rank: Genius
  7. leakim971

    19,600

    0 points yesterday

    Profile
    Rank: Genius
  8. maestropsm

    15,340

    0 points yesterday

    Profile
    Rank: Guru
  9. ansudhindra

    13,300

    0 points yesterday

    Profile
    Rank: Wizard
  10. Zvonko

    12,264

    0 points yesterday

    Profile
    Rank: Genius
  11. micropc1

    10,200

    0 points yesterday

    Profile
    Rank: Master
  12. COBOLdinosaur

    9,800

    200 points yesterday

    Profile
    Rank: Genius
  13. TechHelpr08210

    9,700

    0 points yesterday

    Profile
  14. cyberdyne_dev

    9,500

    0 points yesterday

    Profile
  15. srikanthmadishetti

    8,601

    0 points yesterday

    Profile
    Rank: Guru
  16. brijeshchauhan

    8,468

    0 points yesterday

    Profile
    Rank: Guru
  17. Proculopsis

    8,200

    0 points yesterday

    Profile
    Rank: Sage
  18. kaufmed

    7,468

    0 points yesterday

    Profile
    Rank: Genius
  19. JohnHowlett

    6,000

    0 points yesterday

    Profile
  20. DaveBaldwin

    5,750

    0 points yesterday

    Profile
    Rank: Genius
  21. digicidal

    4,600

    0 points yesterday

    Profile
    Rank: Guru
  22. erikTsomik

    4,500

    0 points yesterday

    Profile
    Rank: Sage
  23. HainKurt

    4,500

    0 points yesterday

    Profile
    Rank: Genius
  24. mplungjan

    4,400

    0 points yesterday

    Profile
    Rank: Savant
  25. sedgwick

    4,000

    0 points yesterday

    Profile
    Rank: Genius

Hall Of Fame