Blog

Saving information in the server

Nov 12, 2009 | English | By Crysfel | 2 Comments | Leer en Espaol

Today we will see how to send the information submitted in a form of Ext JS to the server in order to save it in a database or manipulate it in any way.

Saving information in the server
Author: Crysfel

I'm a software developer with 6+ years of experience, when I'm not developing software I may be writing a tutorial, you can follow me on twitter

In previous tutorials we saw how to load a form with information on the fields, like requesting the information from the server, in this tutorial I will show you how to “submit” the form to send information to the server and save or process the information.

Resources

To continue this tutorial you must download the resources, which contains an HTML that includes a JS file in which I have created a form contained in a window and a PHP file which will process the information sent.

Demonstration

I created a demonstration of the exercise we’re going to do, I recommend you go to test its functionality, is very simple but it explains perfectly what we’ll learn today.

Submit form

Final result

Traditional Submit

If we want to do an ordinary “submit”, without using Ajax and reload the whole page, we only need to set the property “standardSubmit: true”, by default is false.

If we open the file “submitform.js” of the resources, you will see the following code in the method “init”:

this.form = new Ext.form.FormPanel({
	standardSubmit: true, // traditional submit
	url: 'submitform.php',
	border:false,
	labelWidth: 80,
	defaults: {
		xtype:'textfield',
		width: 150
	},
	items:[
		{fieldLabel:'Title',name:'title', allowBlank:false},
		{xtype:'combo',fieldLabel:'Year',name:'year',triggerAction:'all',store:[2009,2008,2007,2006]},
		{xtype:'numberfield',fieldLabel:'Revenues',name:'revenues'},
		{xtype:'textarea',fieldLabel:'Comment',name:'comment'},
		{xtype:'checkbox',fieldLabel:'',labelSeparator:'',boxLabel:'Available',name:'available'}
	]
});

this.win = new Ext.Window({
	id:'mywin',
	title: 'Submit data to the Server',
	bodyStyle: 'padding:10px;background-color:#fff;',
	width:300,
	height:270,
	items:[this.form],
	buttons: [{text:'Save'},{text:'Cancel'}]
});

this.win.show();

We have studied the previous code several times, so I assume that you understand it perfectly. If you’ve noticed, the first setting is “standardSubmit: true” and it enable us to a traditional “submit”, this is actually the only difference of the forms we’ve created in previous tutorials.

make a submit with the buttons save

Until now the buttons do absolutely nothing, they are just being displayed in the form so what we have to do is assign them a “handler” and in this case assign the “scope” we are going to use. Let’s change the code of the button like this:


{text:'Save',handler:this.sendData,scope:this}

Now we have to implement the function “sendData” to do the “submit”.

sendData: function(){
	//submit the form
	this.form.getForm().submit();
}

If you’ve noticed we used the method “getForm()” to have access to the BasicForm in order to do the “submit()”. The component “FormPanel” contains another component called “BasicForm” which is responsible for managing the basic functionalities of a form like: information of the fields, send information to the server, reset the fields, validations, etc.. At the same time, the “FormPanel” is a container that is responsible for managing the “layout”, assign a title and display it in the form of a “Panel” or allocate to other components.

Submit form

Traditional submit, without Ajax

If at this time we click on the button “save”, we will see how the page is reloaded completely.

Make a submit using Ajax

I think this is the part that we’re all interested, let’s see how we can send information using Ajax. The first thing we need to do is remove the configuration “standardSubmit: true” of the form.

this.form = new Ext.form.FormPanel({
	//standardSubmit: true, // remove this property
	url: 'submitform.php',
	border:false,
	labelWidth: 80,
	defaults: {
		xtype:'textfield',
		width: 150
	},
	items:[
		{fieldLabel:'Title',name:'title', allowBlank:false},
		{xtype:'combo',fieldLabel:'Year',name:'year',triggerAction:'all',store:[2009,2008,2007,2006]},
		{xtype:'numberfield',fieldLabel:'Revenues',name:'revenues'},
		{xtype:'textarea',fieldLabel:'Comment',name:'comment'},
		{xtype:'checkbox',fieldLabel:'',labelSeparator:'',boxLabel:'Available',name:'available'}
	]
});

These changes are enough to achieve our goal, if we test the example in this moment we can see in the Firebug console that the parameters are being sent correctly using the method “POST”.

Submit form

Form submit using Ajax

Customize the request method

Sometimes is necessary to change the request method (by default POST) for a different one, in this case we must specify that method we need (GET, POST, PUT, DELETE), we will also send a message if the information was saved successfully or if something caused an error.

this.form.getForm().submit({
	method: 'put',
	success: function(form,action){
		Ext.Msg.alert('Success',action.result.msg);
	},
	failure: function(form,action){
		switch (action.failureType) {
			  case Ext.form.Action.CLIENT_INVALID:
				 Ext.Msg.alert('Failure', 'Form fields may not be submitted with invalid values');
				 break;
			  case Ext.form.Action.CONNECT_FAILURE:
				 Ext.Msg.alert('Failure', 'Ajax communication failed');
				 break;
			  case Ext.form.Action.SERVER_INVALID:
				Ext.Msg.alert('Failure', action.result.msg);
				break;
			  default:
				Ext.Msg.alert('Failure',action.result.msg);
		  }
	}
});

In this example we used the method “PUT” to create a new record in the database, you must be wondering why I used PUT and not POST, right? In future tutorials I will talk about a technique called “REST” which specifies that we must use different existent methods to interact with the server as well as identify the “status” codes in the responses.

The property “success” enables us to configure the function that will be executed if everything went as expected, in this case we’ll only send a message of success:

Submit form

Information saved successfully

The property “failure” allow us to configure a function we want to execute when an error was caused in the server.

Submit form

Something went wrong when saving the information

Who decides when the methods are executed? Great question! Right now the component “FormPanel” expects that the server’s response contains the property “success”, this property is the one that decides which method will be executed, if the property is “true” the function configure in “success” is executed and if it is “false” the function set on property “failure” is executed.

{
    "success":true,
    "msg":"Message example"
}

Also the function configured in “failure” is executed when you cannot establish a communication with the server or an error was caused in the form validation.

Extra parameters

Sometimes it is necessary to send extra parameters to the server, to do this we only need to configure the property “params” in the options of the submit.

this.form.getForm().submit({
	method: 'put',
	params: {
		extraParam: 'Extra params!',
		param2: 'Param 2'
		},
	success: function(form,action){
		Ext.Msg.alert('Success',action.result.msg);
	},
	failure: function(form,action){
		switch (action.failureType) {
			  case Ext.form.Action.CLIENT_INVALID:
				 Ext.Msg.alert('Failure', 'Form fields may not be submitted with invalid values');
				 break;
			  case Ext.form.Action.CONNECT_FAILURE:
				 Ext.Msg.alert('Failure', 'Ajax communication failed');
				 break;
			  case Ext.form.Action.SERVER_INVALID:
				Ext.Msg.alert('Failure', action.result.msg);
				break;
			  default:
				Ext.Msg.alert('Failure',action.result.msg);
		  }
	}
});

Message loading

Finally I will show you how we can mask the window and display a message telling the user that the information is being sent.

First, we need to create the mask and show it before we do the submit.

var mask = new Ext.LoadMask(Ext.get('mywin'), {msg:'Saving. Please wait...'});
mask.show();

The component “Ext.LoadMask” creates a mask for a given element, in this case we are assigning the window that contains the form, the second parameter is a configuration object where we are assigning a message to show; once the “instance” is create we will show the mask using the method “show”.

Submit form

Mask showing the message to the user

Now we must hide it when the server responds, this means that we must invoke the method “hide” in the “success” and “failure”.

success: function(form,action){
		mask.hide(); //hide the mask
		Ext.Msg.alert('Success',action.result.msg);
}

Conclusions

In today’s tutorial we learned some important things, you can see that making a submit is very easy and is completely configurable and can be adapted to our needs.

If you have any questions about this tutorial you can leave a comment or contact us, we will gladly answer your questions. Don’t forget that you can subscribe to our Feeds or read the tutorials by email and of course you can follow us on Twitter (@quizzpot) to be updated.

2 Responses to “Saving information in the server”

  • Ahsan Murshed Feb 24, 2010

    Thanks a lot,your article helps me to solve my problem.

    • Crysfel Feb 25, 2010

      I’m glad to heard that :)

Leave a Reply







Updates

RSS

Subscribe to our feeds to receive updates of our newest posts and free tutorials.

Site search

Maybe we have what you need, would you like to search first?

Donations

Would you buy me a cup of coffee? I am sharing my knowledge and time with you, help this project grow. Thank you!