Learning Ext JS 3

Saving information in the server Más videos

Descripción del tema

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. 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.

Te gustaría recibir más tutoriales como este en tu correo?

Este tutorial pertenece al curso Learning Ext JS 3, te recomiendo revises el resto de los tutoriales ya que están en secuencia de menor a mayor complejidad.

Si deseas recibir más tutoriales como este en tu correo te recomiendo registrarte al curso, si ya eres miembro solo identifícate y registrate al curso, si no eres miembro te puedes registrar gratuitamente!

Si no gustas registrarte en este momento no es necesario! Aún así puedes recibir los nuevos tutoriales en tu correo! Jamás te enviaremos Spam y puedes cancelar tu suscripción en cualquier momento.

¿Olvidaste tu contraseña?

6Comentarios

  • Avatar-6 Ahsan Murshed 24/02/2010

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

    • Avatar-9 Crysfel 25/02/2010

      I'm glad to heard that :)

      • Avatar-2 Lazarus 27/09/2010

        Many hours I spend to learn ExtJs but Your's tutorial are spectacular, fast and clear knowledge u need learn to build something bigger, Thanks Crysfel and waiting for more:)

        • Avatar-9 Ahsan 12/10/2010

          Would you please give me any link extjs with asp.net?

          • Avatar-5 Alonso 13/10/2010

            Yea, Mr.Crysfel: Can you advance some insight about using PUT, with has to do with “REST” , please? You have a very clear and at the same time very instructive way of explain, and at the same time with chunks of knowledge of good size (not small, neither much complex), besides you left open interesting topics for further discussion (like this). !! Thank you ¡¡

            • Avatar-2 Soham Sengupta 14/05/2012

              One simple confusion arises as I do not see the form input values passed to the server, let us say, a Servlet, after submitting the form-panel.

              Instructor del curso

              Crysfel3

              Autor: Crysfel Villa

              Software engineer with more than 7 years of experience in web development.

              Descarga Código Fuente Ver Demostración

              Regístrate a este curso

              Este tutorial pertenece al curso Learning Ext JS 3, revisa todos los tutoriales que tenemos en este mismo curso ya que están en secuencia y van de lo más sencillo a lo más complicado.

              Tendrás acceso a descargar los videos, códigos y material adicional.

              Podrás resolver los ejercicios incluidos en el curso así como los Quizzes.

              Llevarás un registro de tu avance.