Blog

Loading forms remotely

Nov 02, 2009 | English | By Crysfel | 1 Comment | Leer en Espaol

In today’s topic we will see how to fill out a form using Ajax to make a request to the server, we will request the information with an identifier we’ll send as a parameter.

Loading forms remotely
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

We’ve already learned how to fill an Ext JS form through a record, today we’ll fill the form by retrieving information through an Ajax request to the server.

Resources

Before we start this tutorial, please download the resources, which consists of three files and a folder containing images, you must copy these files to the Web server we have been working on, this is very important so we can use Ajax.

Demo

In today’s exercise we will dynamically generate the “Top Ten” list of the most popular movies, when we click on any of these images a form will be displayed, which will be loaded by making a request to the server via Ajax. You can see a demonstration of what we’ll have when we finish this tutorial.

Form loaded with Ajax

Final Example

Information

The most important thing in an application is the information, this time the information is contained in an array on the server, but remember that the information can come from a database such as MySQL, PostgreSQL, Oracle, a Web Service or any other place.

<?php
	header("Content-Type: text/plain"); 

	$all = isset($_GET['all']);
	$movie = isset($_POST['id'])?$_POST['id']:rand(0,9);

	$data = array(
			array('title'=>'G-Force','year'=>2009,'revenues'=>32.2,'comment'=>'Very good movie, it is an awesome movie','available'=>true,'img'=>'images/gforce.jpg'),
			array('title'=>'Harry Potter and the Half-Blood Prince','year'=>2009,'revenues'=>30,'comment'=>'Not to good, but it is ok','available'=>true,'img'=>'images/hpotter.jpg'),
			array('title'=>'The Ugly Truth','year'=>2009,'revenues'=>27,'comment'=>'Another comment to the movie','available'=>false,'img'=>'images/ugly.jpg'),
			array('title'=>'Orphan','year'=>2009,'revenues'=>12.8,'comment'=>'Testing the comment','available'=>'images/orphan.jpg','img'=>'images/orphan.jpg'),
			array('title'=>'Ice Age: Dawn of the Dinosaurs ','year'=>2009,'revenues'=>8.2,'comment'=>'Awesome movie, really good','available'=>true,'img'=>'images/ice.jpg'),
			array('title'=>'Transformers: Revenge of the Fallen','year'=>2009,'revenues'=>8,'comment'=>'Another test','available'=>false,'img'=>'images/transformers.jpg'),
			array('title'=>'The Hangover','year'=>2009,'revenues'=>6.46,'comment'=>'Testing','available'=>true,'img'=>'images/hangover.jpg'),
			array('title'=>'The Proposal','year'=>2009,'revenues'=>6.42,'comment'=>'Comment','available'=>true,'img'=>'images/proposal.jpg'),
			array('title'=>'Public Enemies','year'=>2009,'revenues'=>4.17,'comment'=>'One more comment','available'=>false,'img'=>'images/public.jpg'),
			array('title'=>'Brüno','year'=>2009,'revenues'=>2.72,'comment'=>'nothing to say','available'=>false,'img'=>'images/bruno.jpg')

	);

	if($all){
		$info = $data;
	}else{
		$info = array(
			'success'=>true,
			'data'=> $data[$movie]
		);
	}

	echo json_encode($info);
?>

The most important thing I’d like to mention from the previous code is the parameter “all”, if this parameter is sent in the request, the entire array of objects will be printed in format “json”, if it’s not present it means that we’re requesting only one item.

Requesting information from the server

If you run the HTML in your browser right now you will only see the title, we need to request the information we’re going to display with Ajax, within the method “init” of the main object we will make the request like this:

Ext.Ajax.request({
	url: 'loadform.php',
	params: {all:true}, //requesting all the records
	method: 'GET', //using the method GET
	scope: this,
	success: this.createTopTen // and indicationg what function will process the response
});

As we have requested all the records we will get the following result:

[{"title":"G-Force","year":2009,"revenues":32.2,"comment":"Very good movie, it is an awesome movie","available":true,"img":"images\/gforce.jpg"},{"title":"Harry Potter and the Half-Blood Prince","year":2009,"revenues":30,"comment":"Not to good, but it is ok","available":true,"img":"images\/hpotter.jpg"},{"title":"The Ugly Truth","year":2009,"revenues":27,"comment":"Another comment to the movie","available":false,"img":"images\/ugly.jpg"},{"title":"Orphan","year":2009,"revenues":12.8,"comment":"Testing the comment","available":"images\/orphan.jpg","img":"images\/orphan.jpg"},{"title":"Ice Age: Dawn of the Dinosaurs ","year":2009,"revenues":8.2,"comment":"Awesome movie, really good","available":true,"img":"images\/ice.jpg"},{"title":"Transformers: Revenge of the Fallen","year":2009,"revenues":8,"comment":"Another test","available":false,"img":"images\/transformers.jpg"},{"title":"The Hangover","year":2009,"revenues":6.46,"comment":"Testing","available":true,"img":"images\/hangover.jpg"},{"title":"The Proposal","year":2009,"revenues":6.42,"comment":"Comment","available":true,"img":"images\/proposal.jpg"},{"title":"Public Enemies","year":2009,"revenues":4.17,"comment":"One more comment","available":false,"img":"images\/public.jpg"},{"title":"Br\u00fcno","year":2009,"revenues":2.72,"comment":"nothing to say","available":false,"img":"images\/bruno.jpg"}]

Creating the “Top Ten” List

With the information we received we can create the “Top Ten” list, we will implement the function “createTopTen” where we will decode the JSON first so we can use it correctly and then with the class “DomHelper” we will generate and insert nodes to the DOM.

var info = Ext.decode(response.responseText); //decoding the text we received
Ext.each(info,function(movie){ //iterating the information
	Ext.DomHelper.append('content',{ //and creating an image for each element
		tag:'img',
		src:movie.img,
		alt:movie.title,
		title:movie.title,
		cls: 'movie'
	});
},this);

We have previously studied the class Ext.DomHelper, therefore we must be familiar with its functionality, if you can’t remember about this component I recommend you to review the tutorial where we studied this component.

Form loaded with Ajax

Creating the images for the Top Ten list

Adding “listeners” to the images

The next thing we need to do is add a “listener” to the event “click” of each image we created, so we can display the form with the appropriate information.

Right after we create the images, we’re going to select the DOM nodes, iterate them and we will add the listener to each image.

var items = Ext.DomQuery.select('div[id=content] > img');
Ext.each(items,function(el,i){
	el = Ext.get(el);
	el.on('click',function(){
		this.showDetail(i); //this function will be triggered when the user clicks on an image
	},this);
},this);

In the previous code we can see that the function “showDetail (i);” will be triggered when we click on any image, it is important to mention that you are receiving a parameter “i” which indicates the “id” of the image that has been clicked, this will be useful to request the information to the server.

Creating the form

It’s time to create the form within the “showDetail” function as follows:

var form = new Ext.form.FormPanel({
	url: 'loadform.php', //the URL we  need to load the form
	border:false,
	labelWidth: 80,
	defaults: {
		xtype:'textfield',
		width: 150
	},
	items:[
		{fieldLabel:'Title',name:'title'},
		{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'}
	]
});

At this time of course we must be completely familiar with the code above, the only difference is the property “url”, in this property we configure the URL to make the Ajax request to load the form, don’t forget that it’s very important to use the property “name” in the form fields.

The next thing we need to do is create the window that will contain the previous form.

var win = new Ext.Window({
	title: 'Loading data into a form',
	bodyStyle: 'padding:10px;background-color:#fff;',
	width:300,
	height:270,
	items:[form],
	buttons: [{text:'Save'},{text:'Cancel'}]
});

win.show();

If you click on any image at this moment you will see something like the following picture.

Form loaded with Ajax

Empty form

Requesting the information from the server

We have created the form and appears when clicking on each image, the next thing we will do is fill it with the information depending on the requested image, this is very easy to do because we simply need to invoke the method “load” with the corresponding parameters:

form.getForm().load({params:{id:id}});

We must remember that the JSON format that the server must return is:

{
	"success":true,
	"data":{"title":"The Proposal","year":2009,"revenues":6.42,"comment":"Comment","available":true,"img":"images\/proposal.jpg"}
}

It is very important to return the parameter “success” to “true” (if there wasn’t any error) in order to properly fill out the form, otherwise the component assumes that there was an error in the server and the form won’t get filled.

Form loaded with Ajax

Form loaded with Ajax

Conclusions

Today we learned how to fill out the form using Ajax calls to the server, it is very important that the response contains the property “success: true” so it will work correctly; from my point of view I don’t like that the component requires us to accomplish this, I think it would be better to use a HTTP status to detect whether an error has happened, so we could develop our applications using “REST” (I’ll talk about it in future tutorials) however, the Forms are awesome.

As always, if you have any questions or suggestions please leave a comment and don’t forget to follow us on Twitter (@quizzpot) to be updated on new tutorials or you can subscribe to our Feeds.

One Response to “Loading forms remotely”

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!