20
Mar
11

ExtJS Ajax Form Submission


This page describes the process of creating a extJS HTML form that submits data to a server side resource via Ajax. This page will also cover the validation failure scenario where custom error messages are displayed next to components that have invalid data. This page “simulates” the server side resource, therefore it is not Java / JEE specific and does not require server side programming to implement.

Background

The most popular methods for HTML form submission is to use either “GET” or “POST”.

The “POST” method causes the fields to be encoded into the body of the request. Although this is the preferred method to submit forms with large amount of data, when users arrive on the next page and click refresh they are presented with an annoying message (see below).

Browser Refresh message in Firefox: “To display this page, Firefox must send information that will repeat any action (such as a search or order confirmation) that was performed earlier.”

Browser Refresh message in Internet Explorer 6: “The page can not be refreshed without resending the information. Click Retry to send the information again or click Cancel to return to the page that you were trying to view.”

To most users these messages are confusing/annoying and can result in corrupted data. Imagine a user unknowingly submitting an order twice by clicking refresh on the order confirmation page.

The “GET” method causes the form fields to be encoded into the URL get string. For most large forms or forms that contain binary data this is not an option.

One of the benefits of using extJS for form submission is that with the help of Ajax it allows for the possibility of submitting data to the server in a separate “flow” of execution. Form submissions using Ajax don’t cause the page to reload. The display of the next page is not tied to the submission of the form. This provides the user with a richer client experience and avoids the mess caused by classic HTML form submission.

Requirements

  • Basic Understanding of extJS
  • HTTP Server

Procedure

The following html draws a form on the page. On the bottom of the form there is a Load and Save buttons.

The save button calls “returnSuccess.do”. In order to see validation error messages just replace “returnSuccess.do” with “returnFailure.do”.

index.html

<html>
<head>

<link rel="stylesheet" type="text/css"
    href="http://dev.sencha.com/deploy/ext-3.3.1/resources/css/ext-all.css"/>

<script type="text/javascript"
    src="http://dev.sencha.com/deploy/ext-3.3.1/adapter/ext/ext-base-debug.js">
</script>
<script type="text/javascript"
    src="http://dev.sencha.com/deploy/ext-3.3.1/ext-all-debug.js">
</script>

<script type="text/javascript">

function buildWindow() {

    Ext.QuickTips.init();

    // turn on validation errors beside the field globally
    Ext.form.Field.prototype.msgTarget = 'side';

    var bd = Ext.getBody();

    var fs = new Ext.FormPanel({
        labelWidth: 75, // label settings here cascade unless overridden    
        frame: true,
        title:'Form 2 - Ajax Enabled',
        bodyStyle:'padding:5px 5px 0',
        width: 350,
        defaults: {width: 230},
        waitMsgTarget: true,
        defaultType: 'textfield',        
        
        items: [{
                fieldLabel: 'First Name',
                name: 'firstName',
                allowBlank:false
            },{
                fieldLabel: 'Last Name',
                name: 'lastName'
            },{
                fieldLabel: 'Company',
                name: 'company'
            }, {
                fieldLabel: 'Email',
                name: 'email',
                vtype:'email'
            }, new Ext.form.TimeField({
                fieldLabel: 'Time',
                name: 'time',
                minValue: '8:00am',
                maxValue: '6:00pm'
            })
        ],        

	});
	
	
	// simple button add
	fs.addButton('Load', function(){
	    fs.getForm().load({url:'data.do', waitMsg:'Loading'});
	});

	var onSuccessOrFail = function(form, action) {
		var result = action.result;
		
		if(result.success) {
			Ext.MessageBox.alert('Success', 'Success!');
		} else {
			Ext.MessageBox.alert('Failure', 'Failure!');
		}
		
	}

	// explicit add
	var submit = fs.addButton({
	    text: 'Submit',
	    disabled:true,
	    handler: function(){
	        fs.getForm().submit({
	        	url:'returnSuccess.do', 
//	        	url:'returnFailure.do', 
	        	waitMsg:'Saving Data...', 
	        	submitEmptyText: false,
	        	success : onSuccessOrFail,
	        	failure : onSuccessOrFail
	        });
	    }
	});

	fs.render('form-first');

	fs.on({
	    actioncomplete: function(form, action){
	        if(action.type == 'load'){
	            submit.enable();
	        }
	    }
	});

}
Ext.onReady(buildWindow);
</script>
 
</head>
<body>

<div id="form-first"></div>

</body>
</html>

Data

The following files represent simulated responses from the server side resource.

Load Data

The “data.do” represents the name, company and email information for a single person. It is retrieved from the server when the user clicks the load button. URL specified in “index.html” line 61 (highlighted) above.

data.do

{
    success : true,
    data    : {
        firstName : 'Jack',
        lastName  : 'Slocum',
        company   : 'Slocum LLC',
        email     : 'jack@slocum.com',
        time      : '9:45 AM'
    }
}

Save Data

When the user clicks the “save” button the URL specified in “index.html” line 81 (highlighted) will be called and the extJS component is expecting the following response from the server.

returnSuccess.do

{success: true, msg : 'Thank you for your submission.'}

Save Data with Failure

In the case the server side resource returns validation failures the extJS component is expecting them in the following format from the server. The failure messages displayed below display next to their prospective fields.

returnFailure.do

{
   success : false,
   msg     : 'This is an example error message',
   errors  : {
      firstName : 'Sample Error for First Name',
      lastName  : 'Sample Error for Last Name'
   }
}

Run the Example

Since we are making Ajax requests a Web Server is required. Save all the files and navigate to index.html using a web browser.

Click on Load to load the data. Click on Save to view the success message. In order to view the validation failure messages replace the URL on line 81 with “returnFailure.do”.

Summary

The example described on this page is very simple. However it does cover some of the basics of loading and submitting an extJS form using an Ajax.

The chances of this example above being used on an actual page are slim. Reason??? What happens after a form is submitted? The answer is by default… NOTHING…

After thinking about the above I gathered my thoughts and am in the process of writing Part II of this page which covers “User Interactions” with ExtJS enabled web applications. (soon to come).

That’s all for now.

About these ads

1 Response to “ExtJS Ajax Form Submission”


  1. 1 ucassh
    April 16, 2011 at 8:34 pm

    Thanx, I’ve found solution of my problem :)


Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 58 other followers

March 2011
S M T W T F S
« Feb   Apr »
 12345
6789101112
13141516171819
20212223242526
2728293031  

Blog Stats

  • 580,576 hits

Follow

Get every new post delivered to your Inbox.

Join 58 other followers

%d bloggers like this: